form表单的enctype的取值必须是multipart/form-data
。
默认值是application/x-www-form-urlencoded
。
method的取值必须是post。
提供一个文件选择域<input type="file">
当form表单的enctype取值不是默认值后,request.getParameter()
将失效。设置为默认值时,数据格式为key=value&key=value
的格式。当form表单设置为multipart/form-data
时,请求正文每一部分都是MIME类型描述的正文。
使用Commons-fileupload组件实现文件上传,需要导入该组件的支撑jar包:commons-io-2.4
,commons-fileupload-1.3.1
。
package com.example.controller;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/fileupload1")
public String fileupload1(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("文件上传");
//使用fileupload组件完成上传
String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
//判断该路径是否存在
File file =new File(realPath);
if(!file.exists()){
System.out.println("文件");
file.mkdirs();
}
//解析request对象,获取上传文件项
DiskFileItemFactory factory= new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
//解析request
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
//判断当item是否为上传文件项
if(item.isFormField()){
//说明普通表单项
}
else{
//上传文件项
//获取上传文件的名称
String filename = item.getName();
//把文件的名称设置唯一值。uuid,设置时,要把-去掉。
String uuid = UUID.randomUUID().toString().replace("-", "");
filename=uuid+"_"+filename;
item.write(new File(realPath,filename));
//删除临时文件
item.delete();
}
}
return "success";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="/user/fileupload1" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
首先配置文件解析器,在springmvc.xml文件中
<!--配置文件解析器对象,要求id名必须是multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/>
<!--最大上传大小,单位是字节 10485760是10M-->
</bean>
注意,id是确定的。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="/file/fileupload2" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"/><br>
<input type="submit" value="上传">
</form>
</body>
</html>
package cn.example.Controller;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/file")
public class fileController {
@RequestMapping("/fileupload2")
public String fileupload2(HttpServletRequest request, MultipartFile upload) throws IOException {
//注意:MultipartFile参数名称必须和表单文件选择的input标签的name属性名相同。
System.out.println("springmvc文件上传");
String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(realPath);
File file=new File(realPath);
if(!file.exists()){
file.mkdirs();
}
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-","");
upload.transferTo(new File(realPath,filename));
return "success";
}
}
注意:方法的MultipartFile参数名称必须和表单文件选择的input标签的name属性名相同。
需要两个jar包:jersey-client-1.18.1.jar
,jersey-core-1.18.1.jar
。
package cn.itcast.controller;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/fileupload3")
public String fileuoload3(MultipartFile upload) throws Exception {
System.out.println("跨服务器文件上传...");
// 定义上传文件服务器路径
String path = "http://localhost:9090/uploads/";
// 说明上传文件项
// 获取上传文件的名称
String filename = upload.getOriginalFilename();
// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 创建客户端的对象
Client client = Client.create();
// 和图片服务器进行连接
WebResource webResource = client.resource(path + filename);
// 上传文件
webResource.put(upload.getBytes());
return "success";
}
}
package cn.example.Controller;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/file")
public class fileController {
@RequestMapping("/filedownload")
public String filedownLoad(HttpServletRequest request,HttpServletResponse response) throws IOException {
String filepath = "D:\\sources\\Java\\springmvc\\day02_springmvc_fileupload\\download\\";
String filename = "abc.png";
ServletOutputStream outputStream=response.getOutputStream();
byte[] bytes= FileUtils.readFileToByteArray(new File(filepath,filename));
response.setHeader("Content-Disposition","attchment;filename="+filename);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
return "success";
}
}
推荐使用response方式,这种方式可以以json格式给前台返回提示信息。
package cn.example.Controller;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/file")
public class fileController {
@RequestMapping("/filedownload2")
public ResponseEntity<byte[]> download2() throws IOException {
String filepath = "D:\\sources\\Java\\springmvc\\day02_springmvc_fileupload\\download\\";
String filename = "abc.png";
byte[] bytes=FileUtils.readFileToByteArray(new File(filepath,filename));
HttpHeaders httpHeaders =new HttpHeaders();
httpHeaders.set("Content-Disposition","attchment;filename="+filename);
ResponseEntity<byte[]> entity=new ResponseEntity<>(bytes,httpHeaders, HttpStatus.OK);
return entity;
}
}
原文:https://www.cnblogs.com/acknowledge/p/14460405.html