您的位置:首页 > 编程语言 > Java开发

13Spring文件上传下载

2016-07-12 15:39 246 查看
1实现文件上传

用户必须能够上传图片,因此需要文件上传的功能。比较常见的文件上传组件有Commons FileUpload(http://jakarta.apache.org/commons/fileupload/a>)和COS FileUpload(http://www.servlets.com/cos),Spring已经完全集成了这两种组件,这里我们选择Commons FileUpload。

由于Post一个包含文件上传的Form会以multipart/form-data请求发送给服务器,必须明确告诉 DispatcherServlet如何处理MultipartRequest。首先在spring-servlet.xml中声明一个 MultipartResolver:

    <bean id="multipartResolver"  

        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  

        <!-- 设置上传文件的最大尺寸为1MB -->  

        <property name="maxUploadSize">  

            <value>1048576</value>  

        </property>  
<property name="maxInMemorySize" value="4096" />

    </bean>  

另外WEB-INF/lib下必加入:commons-fileupload.jar与commons-io-1.4.jar二个文件 

这样一旦某个Request是一个MultipartRequest,它就会首先被MultipartResolver处理,然后再转发相应的Controller。

在UploadImageController中,将HttpServletRequest转型为MultipartHttpServletRequest,就能非常方便地得到文件名和文件内容。下面是我们在Controller中对应的上传方法: 

@RequestMapping(value = "/userFile.do", params = "upload",method = RequestMethod.POST)
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, BindException errors)
throws Exception {

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
.getFile("file");

//获得request里的其他参数
String name = multipartRequest.getParameter("name");

System.out.println("upload file name: " + name);
// 获得文件名:
String realFileName = file.getOriginalFilename();
System.out.println("获得文件名:" + realFileName);

/**页面控件的文件流**/    

MultipartFile multipartFile = multipartRequest.getFile("file");      

/**获取文件的后缀**/    

String suffix = multipartFile.getOriginalFilename().substring  

(multipartFile.getOriginalFilename().lastIndexOf(".")); 

// 获取路径
String ctxPath = request.getServletContext().getRealPath("/")+ "userFiles/";
// 创建存放上传文件的文件夹
File dirPath = new File(ctxPath);
if (!dirPath.exists()) {
dirPath.mkdir();
}
File uploadFile = new File(ctxPath + realFileName);
FileCopyUtils.copy(file.getBytes(), uploadFile);
System.out.println("获得上传文件的路径:" + uploadFile.getPath());
request.setAttribute("fileName", realFileName);
return new ModelAndView("success");
}

简单的上传界面:

<%@ page language="java" pageEncoding="UTF-8"%>

<%@include file="/common/taglibs.jsp"%>

<html>

  <head>

    <title>上传文件</title>

  </head>

<body>

<form action="${ctx }/userFile.do?upload" method="post" ENCTYPE="multipart/form-data">

<input type="File" name="file">

<input type="hidden" name="name" value="张三">

<input type="submit" value="提交"/>

</form>

</body>

</html>

2文件下载实例

首先是后台处理方法:

/**
* 下载文件
* @param resp
* @return
*/
@RequestMapping(value = "/userFile.do", params = "download")
@ResponseBody
void downLoadFile(HttpServletRequest request,HttpServletResponse response) {
Map<String, String> paramMap = Utils.getParamMapUtf8new(request);

String fileCode=paramMap.get("fileCode");
String filePath=paramMap.get("filePath");
String fileName=paramMap.get("fileName");
try {
//具体的下载方法
downloadLocal(filePath,fileName,response);
} catch (FileNotFoundException e) {
userFileDao.removeOneByCode(fileCode);
}
}

public void downloadLocal(String filePath,String fileName,HttpServletResponse response) throws FileNotFoundException {
InputStream inStream = new FileInputStream(filePath);// 文件的存放路径
response.reset();
response.setContentType("bin");
try {
//需要进行编码转换否则中文文件名不能显示
fileName=new String(fileName.getBytes("UTF-8"), "ISO_8859_1");
} catch (UnsupportedEncodingException e1) {}
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 循环取出流中的数据
byte[] b = new byte[100];
int len;
try {
while ((len = inStream.read(b)) > 0)
response.getOutputStream().write(b, 0, len);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

jsp页面上的下载方法

<span onclick="downLoadFile('${data.userFileCode}','${data.userFileName }','${ data.userFilePath}')" title="${data.userFileName}">下载</span>

function downLoadFile(fileCode,fileName,filePath) {

//var str="&fileName="+encodeURIComponent(fileName)+"&fileCode="+encodeURIComponent(fileCode)+"&filePath="+encodeURIComponent(filePath);

var str="&fileName="+fileName+"&fileCode="+fileCode+"&filePath="+filePath;

document.location.href="${ctx}/userFile.do?download"+str;  
}



<a href=""${ctx}/userFile.do?download&fileCode=${data.userFileCode}&fileName=${data.userFileName }&filePath=${ data.userFilePath}">下载</a>

3Java文件下载的几种方式

public HttpServletResponse download(String path, HttpServletResponse response) {

try {

// path是指欲下载的文件的路径。

File file = new File(path);

// 取得文件名。

String filename = file.getName();

// 取得文件的后缀名。

String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

try {

//转换编码否则中文文件名有问题

 fileName=new String(fileName.getBytes("UTF-8"), "ISO_8859_1");

} catch (UnsupportedEncodingException e1) {}

// 以流的形式下载文件。

InputStream fis = new BufferedInputStream(new FileInputStream(path));

byte[] buffer = new byte[fis.available()];

fis.read(buffer);

fis.close();

// 清空response

response.reset();

// 设置response的Header

response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));

response.addHeader("Content-Length", "" + file.length());

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

response.setContentType("application/octet-stream");

toClient.write(buffer);

toClient.flush();

toClient.close();

} catch (IOException ex) {

ex.printStackTrace();

}

return response;

}

public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {

// 下载本地文件

String fileName = "Operator.doc".toString(); // 文件的默认保存名

try {

//转换编码否则中文文件名有问题

 fileName=new String(fileName.getBytes("UTF-8"), "ISO_8859_1");

} catch (UnsupportedEncodingException e1) {}

// 读到流中

InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径

// 设置输出的格式

response.reset();

response.setContentType("bin");

response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

// 循环取出流中的数据

byte[] b = new byte[100];

int len;

try {

while ((len = inStream.read(b)) > 0)

response.getOutputStream().write(b, 0, len);

inStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

public void downloadNet(HttpServletResponse response) throws MalformedURLException {

// 下载网络文件

int bytesum = 0;

int byteread = 0;

URL url = new URL("windine.blogdriver.com/logo.gif");

try {

URLConnection conn = url.openConnection();

InputStream inStream = conn.getInputStream();

FileOutputStream fs = new FileOutputStream("c:/abc.gif");

byte[] buffer = new byte[1204];

int length;

while ((byteread = inStream.read(buffer)) != -1) {

bytesum += byteread;

System.out.println(bytesum);

fs.write(buffer, 0, byteread);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

//支持在线打开文件的一种方式

public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {

File f = new File(filePath);

if (!f.exists()) {

response.sendError(404, "File not found!");

return;

}

BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));

byte[] buf = new byte[1024];

int len = 0;

response.reset(); // 非常重要

if (isOnLine) { // 在线打开方式

URL u = new URL("file:///" + filePath);

response.setContentType(u.openConnection().getContentType());

response.setHeader("Content-Disposition", "inline; filename=" + f.getName());

// 文件名应该编码成UTF-8

} else { // 纯下载方式

try {

//转换编码否则中文文件名有问题

 fileName=new String(fileName.getBytes("UTF-8"), "ISO_8859_1");

} catch (UnsupportedEncodingException e1) {}

response.setContentType("application/x-msdownload");

response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());

}

OutputStream out = response.getOutputStream();

while ((len = br.read(buf)) > 0)

out.write(buf, 0, len);

br.close();

out.close();

}

******************************

上传图片生成缩略图

当用户上传了图片后,必须生成缩略图以便用户能快速浏览。我们不需借助第三方软件,JDK标准库就包含了图像处理的API。我们把一张图片按比例缩放到120X120大小,以下是关键代码:

public static void createPreviewImage(String srcFile, String destFile) {   

        try {   

            File fi = new File(srcFile); // src   

            File fo = new File(destFile); // dest   

            BufferedImage bis = ImageIO.read(fi);   

  

            int w = bis.getWidth();   

            int h = bis.getHeight();   

            double scale = (double) w / h;   

            int nw = IMAGE_SIZE; // final int IMAGE_SIZE = 120;   

            int nh = (nw * h) / w;   

            if (nh > IMAGE_SIZE) {   

                nh = IMAGE_SIZE;   

                nw = (nh * w) / h;   

            }   

            double sx = (double) nw / w;   

            double sy = (double) nh / h;   

  

            transform.setToScale(sx, sy);   

            AffineTransformOp ato = new AffineTransformOp(transform, null);   

            BufferedImage bid = new BufferedImage(nw, nh,   

                    BufferedImage.TYPE_3BYTE_BGR);   

            ato.filter(bis, bid);   

            ImageIO.write(bid, " jpeg ", fo);   

        } catch (Exception e) {   

            e.printStackTrace();   

            throw new RuntimeException(   

                    " Failed in create preview image. Error:  "  

                            + e.getMessage());   

        }   

    }  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring