日期:2014-05-18  浏览次数:20737 次

请问怎么用jsp下载图片


在网上查过一些 比较零碎的资料

2种方案

1)不用第三方库
2)smartupload


我想要比较完整的代码



谢谢

------解决方案--------------------
SF,帮你顶起来.让更多人看到来帮助你.
------解决方案--------------------
写个servlet 重定向输出文件流就可以了 ,代码放在jsp 中也可以
Java code

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadFileServlet extends HttpServlet {


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename=request.getParameter("filename");
        response.reset();
        response.setContentType("application/x-download");
        UploadFile upload = new UploadFile();
        String filepath = upload.getDownloadFilePath();
        String filenamedownload = filepath + java.io.File.separator + filename;
        String filenamedisplay = java.net.URLEncoder.encode(filename, "UTF-8");
        filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + filenamedisplay);

        OutputStream output = null;
        FileInputStream fis = null;
        try {
            output = response.getOutputStream();
            fis = new FileInputStream(filenamedownload);

            byte[] b = new byte[1024];
            int i = 0;

            while ((i = fis.read(b)) > 0) {
                output.write(b, 0, i);
            }
            output.flush();
        } catch (Exception e) {
            System.out.println("Close the download file windows!");
        } finally {
            if (fis != null) {
                fis.close();
                fis = null;
            }
            if (output != null) {
                output.close();
                output = null;
            }
        }
    }
}