下载文件默认文件名中文乱码问题的解决一般是因为没有转码导致。
package sample.server;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Frame;
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet( HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{
//此函数对应之前的 Frame frame =
//new Frame( GWT.getModuleBaseURL() + "filedownload" + "?id=downloadiframe"+"&filename=" + filename );
//传文件名那个简单啊
String filename = req.getParameter("filename");
//这边你要自己决定从哪下载的文件!! 我是把上传路径直接给他了
//这里说下。。我先前没自己创建 uploads 结果十分悲剧
//记得在 war 路径下创建 !!
String filepath = req.getRealPath("/uploads");
File file = new File( filepath+"/"+filename );
FileInputStream fis = new FileInputStream(file);
resp.addHeader("Content-Disposition","attachment; filename=" + filename );//此处设置默认下载文件名,如果是中文肯定乱码,需要做一次ULL转码,Server.UrlEncode(filename)
ServletOutputStream out = resp.getOutputStream();
resp.setBufferSize(32768);
int bufSize = resp.getBufferSize();
byte[] buffer = new byte[bufSize];
BufferedInputStream bis = new BufferedInputStream(fis,bufSize);
int bytes;
while ((bytes = bis.read(buffer, 0, bufSize)) >= 0)
out.write(buffer, 0, bytes);
bis.close();
fis.close();
out.flush();
out.close();
}
}