?<!-- 配置用于上传的MultipertResolver --> ?
??????? <bean id="multipartResolver" ?
??????????? class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> ?
??????????? <!-- 设置字符编码 --> ?
??????????? <property name="defaultEncoding" value="UTF-8"></property> ?
??????????? <!-- 设置上传的maxUploadSize --> ?
??????????? <property name="maxUploadSize" value="102400"></property> ?
??????? </bean>
package com.imooc.controller;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadAction {
?? ?// 文件上传功能
?? ?@RequestMapping("/fileUpload.action")
?? ?public String fileUpload(MultipartFile file,HttpServletRequest request) throws Exception {
?? ??? ?if (!file.isEmpty()) {
?? ??? ??? ?//打印文件的名称
?? ??? ??? ?//System.out.println("FileName:" + file.getOriginalFilename());
?? ??? ??? ?//确定上传文件的位置?? ??? ?
?? ??? ??? ?String path = request.getServletContext().getRealPath("/fileupload"); ?
?? ??? ??? ?//String path = "E:/WorkSpace1/SpringMVCDemo/WebContent/WEB-INF/fileupload";
?? ??? ??? ?File newFile = new File(path, file.getOriginalFilename());
?? ??? ??? ?if (!newFile.exists()) {
?? ??? ??? ??? ?newFile.createNewFile();
?? ??? ??? ?}
?? ??? ??? ?// 上传
?? ??? ??? ?file.transferTo(newFile);
?? ??? ?}
?? ??? ?//上传成功后转发到success.jsp
?? ??? ?return "success";
?? ?}
}
注意:form的一个属性值? ???enctype="multipart/form-data"
<form action="fileUpload.action" method="post" enctype="multipart/form-data">
File<input type="file" name="file">
<input type="submit">
</form>
============================================================================================================================
package com.imooc.controller;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class DownLoadAction {
@RequestMapping("/fileDownLoad.action")
public ResponseEntity<byte[]> fileDownload() throws Exception {
//文件的路径,当然你可以自己拼接
String path = "E:/WorkSpace1/SpringMVCDemo/WebContent/WEB-INF/fileupload/1.png";
File file = new File(path);
HttpHeaders headers = new HttpHeaders();
// 为了解决中文名称乱码问题
String fileName = new String(file.getName().getBytes("UTF-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
}
<a href="fileDownLoad.action">文件下载</a>