在使用springMVC进行系统实现时,springMVC默认的解析器里面是没有加入对文件上传的解析的。但如果你想使用springMVC对文件上传的解析器来处理文件上传的时候就需要在spring的applicationContext里面加上springMVC提供的MultipartResolver的申明。客户端每次进行请求的时候,springMVC都会检查request里面是否包含多媒体信息,如果包含了就会使用MultipartResolver进行解析,springMVC会使用一个支持文件处理的MultipartHttpServletRequest来包裹当前的HttpServletRequest,然后使用MultipartHttpServletRequest就可以对文件进行处理了。Spring已经为我们提供了一个MultipartResolver的实现,我们只需要拿来用就可以了,那就是org.springframework.web.multipart.commons.CommsMultipartResolver。因为springMVC的MultipartResolver底层使用的是Commons-fileupload,所以还需要加入对Commons-fileupload.jar的支持。
首先,配置文件添加
<!-- 这里申明的id必须为multipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>
CommonsMultipartResolver允许设置的属性有:
defaultEncoding:表示用来解析request请求的默认编码格式,当没有指定的时候根据Servlet规范会使用默认值ISO-8859-1。
当 request自己指明了它的编码格式的时候就会忽略这里指定的 defaultEncoding。
uploadTempDir:设置上传文件时的临时目录,默认是Servlet容器的临时目录。
maxUploadSize:设置允许上传的最大文件大小,以字节为单位计算。当设为-1时表示无限制,默认是-1。
maxInMemorySize:设置在文件上传时允许写到内存中的最大值,以字节为单位计算,默认是10240。
然后在 Controller 层就可以接收到了。再转到imp去处理
@Controller
public class Controller {
@RequestMapping(value = "/upload", method=RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
//当要同时上传多个文件时,可以给定多个MultipartFile参数
if (!file.isEmpty()) {
//第一种获取文件存储
String ss = "xxx/xxxx/xxx.png";
byte[] bytes = file.getBytes();
BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(ss)));
stream.write(bytes);
stream.flush();
stream.close();
//第二种获取文件存储
String path = "xxx/xxxx/xxx/";
String fileName = "aaa.png";
File targetFile = new File( path , fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
file.transferTo(targetFile);
}
}
}
像平常不用框架的话,基本就是原生的 servlet上传了
这个用的是 jspsmartupload
@WebServlet(name="UploadImgServlet", urlPatterns={"/services/UploadImgServlet"})
public class UploadImgServlet extends HttpServlet {
// @Autowired
// private BizDao bizDao;
@Override
public void init() throws ServletException {
// ServletContext servletContext = this .getServletContext();
// WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
// bizDao = (BizDao)ctx.getBean("bizDao" );
}
public void doGet(HttpServletRequest request, HttpServletResponse resp)
throws ServletException, IOException {
doPost(request, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html,charset=UTF-8");
SmartUpload smartUpload = new SmartUpload();
try {
// 添加缓存
smartUpload.initialize(this.getServletConfig(), req, resp);
smartUpload.upload();
com.jspsmart.upload.File smartFile = smartUpload.getFiles()
.getFile(0);
if (!smartFile.isMissing()) {
String path = getServletContext().getRealPath("");
// address + fileName
String saveFileName = path.substring(0 , path.lastIndexOf("\\") + 1) + "upload" + "/" + smartFile.getFileName();
System.out.println("===saveFileName==="+ saveFileName);
// 保存图片
smartFile.saveAs(saveFileName, smartUpload.SAVE_PHYSICAL);
resp.getWriter().print("http://192.168.0.149:8081/upload/" +
smartFile.getFileName());
} else {
resp.getWriter().print("0");
}
} catch (Exception e) {
resp.getWriter().print("0");
e.printStackTrace();
resp.getWriter().print(e);
}
}
}
原生的慢慢解析http协议的方式
@WebServlet(name="ImageUploadServlet", urlPatterns={"/services/imageUpload"})
public class ImageUploadServlet extends HttpServlet {
private static Logger logger = LoggerFactory.getLogger(ImageUploadServlet.class);
private String rootDir = null;
private String contextPath = null;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.write("call POST with multipart form data");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("============================开始上传图片============================");
rootDir = this.getServletConfig().getServletContext().getRealPath("/");//项目根目录
contextPath = request.getContextPath();
System.out.println("=====rootDir==="+ rootDir);
ResponseBean resp = new ResponseBean();
ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
PrintWriter writer = response.getWriter();
uploadHandler.setHeaderEncoding("utf-8");
Map<String,String> fieldMap = new HashMap<String, String>();
Map<String, String> imageConfigMap = SysConfig.getImageServer("1");
System.out.println("====imageConfigMap==="+ imageConfigMap);
try {
System.out.println("request"+ request);
List<FileItem> items = uploadHandler.parseRequest(request);
System.out.println("==List<FileItem>=="+ items);
for (FileItem item : items) {
if(item.isFormField()){
String name = item.getFieldName();
BufferedReader br = new BufferedReader(new InputStreamReader(item.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = null;
while((line = br.readLine()) != null){
sb.append(line);
}
fieldMap.put(name, sb.toString().trim());
}
}
for (FileItem item : items) {
if (!item.isFormField()) {
String dirName = imageConfigMap.get("tempDir");
File fileDir = null;
if(rootDir.trim().endsWith(File.separator)){
fileDir = new File(rootDir + dirName);
}else{
fileDir = new File(rootDir + File.separator + dirName);
}
if(!fileDir.isDirectory()){
System.out.println("====创建文件夹"+ fileDir.getAbsolutePath());
fileDir.mkdirs();
}
String fileName = DateTimeUtil.getTimeStamp()+CommonTool.getRandom(3,1000)+item.getName().substring(item.getName().lastIndexOf("."));
System.out.println("===文件名=="+ fileName );
File file = new File(fileDir.getPath()+"/"+fileName);
if(!file.exists()){
file.createNewFile();
}
item.write(file);
//判断类型进行 图片的转换和 转移
handleImage(fieldMap, file, resp);
break; // assume we only get one file at a time
}
}
} catch (Exception e) {
resp.setCode(2);
resp.setMessage("上传失败:"+e.toString());
e.printStackTrace();
throw new RuntimeException(e);
} finally {
resp.setTimestamp(DateTimeUtil.getTimeStamp());
String result = JSON.toJSONString(resp);
writer.write(result);
logger.debug(result);
logger.info("============================结束上传图片============================");
writer.close();
}
}
private void handleImage(Map<String,String> fieldMap, File imageFile, ResponseBean resp){
Map<String, String> imageConfigMap = SysConfig.getImageServer("1");
//开始事物
// SqlSession session = SessionFactory.getSessionFactory().openSession();
File destFile = null;
try {
String imageType = fieldMap.get("ImageType"); //图片类型
System.out.println("==imageType=="+ imageType);
if(imageType.equalsIgnoreCase("headPhotos")){ // 如果是头像
String user_id = fieldMap.get("UserId"); //用户ID
String user_type = fieldMap.get("UserType"); //用户类型
System.out.println("==user_id=="+ user_id);
System.out.println("==user_type=="+ user_type);
File fileDir = null;
if(rootDir.trim().endsWith(File.separator)){
fileDir = new File(rootDir + "images"+File.separator+imageType+File.separator+user_type);
}else{
fileDir = new File(rootDir + File.separator + "images"+File.separator+imageType+File.separator+user_type);
}
if(!fileDir.isDirectory()){
fileDir.mkdirs();
}
System.out.println("===fileDir.getPath()==="+ fileDir.getPath());
destFile = new File(fileDir.getPath()+File.separator+user_id+"_"+DateTimeUtil.getTimeStamp()+imageFile.getName().substring(imageFile.getName().lastIndexOf(".")));
System.out.println("===destFile.getPath()==="+ destFile.getPath());
FileUtils.copyFile(imageFile, destFile);
imageFile.delete();
/** 数据插入 ImageDAO dao = session.getMapper(ImageDAO.class); **/
Map<String, Object> paramsMap = new HashMap<String,Object>();
paramsMap.put("id", user_id);
paramsMap.put("user_type", user_type);
paramsMap.put("head_photo", "images"+"/"+imageType+"/"+user_type+"/"+destFile.getName());
/** int num = dao.modHeadPhoto(paramsMap); **/
System.out.println("======返回值=========");
Map<String, Object> data = new HashMap<String,Object>();
data.put("image_name", destFile.getName());
data.put("image_url", imageConfigMap.get("showServer")+contextPath+"/"+paramsMap.get("head_photo"));
resp.setData(data);
}
} catch (Exception e) {
e.printStackTrace();
resp.setCode(3);
resp.setMessage("上传失败:"+e.toString());
// session.rollback();
} finally{
// session.commit();
try {
// if(!session.getConnection().isClosed()){
// session.close();
// }
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
客户端测试,可以用工具
或者java 代码直接测
public class DDDD {
public static void main(String[] args) {
try {
//普通参数
ArrayList<FormFieldKeyValuePair> ffkvp = new ArrayList<FormFieldKeyValuePair>();
//文件参数
ArrayList<UploadFileItem> ufi = new ArrayList<UploadFileItem>();
ffkvp.add(new FormFieldKeyValuePair("UserId", "50"));//其他参数
ffkvp.add(new FormFieldKeyValuePair("UserType", "cy"));
ffkvp.add(new FormFieldKeyValuePair("ImageType", "headPhotos"));
ffkvp.add(new FormFieldKeyValuePair("UserName", "啦啦啦啦啦"));
ffkvp.add(new FormFieldKeyValuePair("Phone", "782738738"));
// ffkvp.add(new FormFieldKeyValuePair("UserSex", "1"));
// ffkvp.add(new FormFieldKeyValuePair("Email", "[email protected]"));
// ffkvp.add(new FormFieldKeyValuePair("Address", "地址:"));
ffkvp.add(new FormFieldKeyValuePair("IDcard", "09090909090909090"));
ufi.add(new UploadFileItem("file","d://wowowo.png"));
sendHttpPostRequest("http://192.168.0.197:8091/Server/services/imageUpload",
ffkvp,ufi);
//
// sendHttpPostRequest("http://192.168.0.197:8091/Server/user/changeInfo.do",
// ffkvp,ufi);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
private static final String BOUNDARY = "----------HV2ymHFg03ehbqgZCaKO6jyH";
public static String sendHttpPostRequest(String serverUrl,
ArrayList<FormFieldKeyValuePair> generalFormFields,
ArrayList<UploadFileItem> filesToBeUploaded) throws Exception {
// 向服务器发送post请求
URL url = new URL(serverUrl/* "http://127.0.0.1:8080/test/upload" */);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
// 头
String boundary = BOUNDARY;
// 传输内容
StringBuffer contentBody = new StringBuffer("--" + BOUNDARY);
// 尾
String endBoundary = "\r\n--" + boundary + "--\r\n";
OutputStream out = connection.getOutputStream();
// 1. 处理文字形式的POST请求
for (FormFieldKeyValuePair ffkvp : generalFormFields) {
contentBody.append("\r\n")
.append("Content-Disposition: form-data; name=\"")
.append(ffkvp.key + "\"")
.append("\r\n")
.append("\r\n")
.append(ffkvp.value)
.append("\r\n")
.append("--")
.append(boundary);
}
String boundaryMessage1 = contentBody.toString();
out.write(boundaryMessage1.getBytes("utf-8"));
// 2. 处理文件上传
for (UploadFileItem ufi : filesToBeUploaded) {
contentBody = new StringBuffer();
contentBody.append("\r\n")
.append("Content-Disposition:form-data; name=\"")
.append(ufi.formFieldName + "\"; ") // form中field的名称
.append("filename=\"")
.append(ufi.fileName + "\"") // 上传文件的文件名,包括目录
.append("\r\n")
.append("Content-Type:application/octet-stream")
.append("\r\n\r\n");
String boundaryMessage2 = contentBody.toString();
out.write(boundaryMessage2.getBytes("utf-8"));
// 开始真正向服务器写文件
File file = new File(ufi.fileName);
DataInputStream dis = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[(int) file.length()];
bytes = dis.read(bufferOut);
out.write(bufferOut, 0, bytes);
dis.close();
contentBody.append("------------HV2ymHFg03ehbqgZCaKO6jyH");
String boundaryMessage = contentBody.toString();
out.write(boundaryMessage.getBytes("utf-8"));
// System.out.println(boundaryMessage);
}
out.write("------------HV2ymHFg03ehbqgZCaKO6jyH--\r\n"
.getBytes("UTF-8"));
// 3. 写结尾
out.write(endBoundary.getBytes("utf-8"));
out.flush();
out.close();
// 4. 从服务器获得回答的内容
String strLine = "";
String strResponse = "";
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"utf-8"));
while ((strLine = reader.readLine()) != null) {
strResponse += strLine + "\n";
}
System.out.print(strResponse);
return strResponse;
}
static class FormFieldKeyValuePair {
// such as "username" in "<inputtype="text" name="username"/>"
public String key;
// such as "Patrick" the abovementioned formfield "username"
public String value;
public FormFieldKeyValuePair(String key, String value){
this.key = key;
this.value = value;
}
}
static class UploadFileItem implements Serializable{
// such as "upload1" in "<inputtype="file" name="upload1"/>"
public String formFieldName;
// such as "E:\\some_file.jpg"
public String fileName;
public UploadFileItem(String formFieldName, String fileName){
this.formFieldName = formFieldName;
this.fileName = fileName;
}
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。