java上传文件常见几种方式

1、ServletFileUpload

  表单提交中当提交数据类型是multipare/form-data类型的时候,如果我们用servlet去做处理的话,该http请求就会被servlet容器,包装成httpservletRequest对象

  ,在由相应的servlet进行处理。

    

package com.jws.app.operater.service.impl;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service; import net.sf.json.JSONObject; import com.jws.app.operater.data.UserInfoMapper;
import com.jws.app.operater.model.UserInfo;
import com.jws.app.operater.service.PersionPhoteAuthServer;
import com.jws.common.constant.Constants;
import com.jws.common.constant.ConstantsCode;
import com.jws.common.util.JiveGlobe;
import com.jws.common.util.ResultPackaging; @Service("persionPhoteAuthServerImpl")
public class PersionPhoteAuthServerImpl implements PersionPhoteAuthServer {
@Resource
private UserInfoMapper userInfoMapper;
private final Logger logger = Logger.getLogger(this.getClass()); @Override
public JSONObject uploadPhoto(HttpServletRequest reques) {
JSONObject returnObject = new JSONObject();
String path = Constants.imageUrl;
File repositoryFile = new File(path);
if (!repositoryFile.exists()) {repositoryFile.mkdirs();}
FileItemFactory factory = new DiskFileItemFactory(1024 * 32,repositoryFile);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
upload.setSizeMax(1024 * 1024 * 500);
List<?> fileItr = null;
try {
fileItr = upload.parseRequest(reques);
// 讲非文件值放在map中
HashMap<String, String> map = new HashMap<>();
Iterator<?> iter = fileItr.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
map.put(item.getFieldName(), item.getString());
}
}
// 验证参数
if (map == null || !map.containsKey("openid")) {
returnObject =ResultPackaging.dealJsonObject(ConstantsCode.RESULT_CODE_FAIL, ConstantsCode.CODE_LACK_PARAMETER, null);
return returnObject;
}
String openid = map.get("openid");
//处理文件
boolean isTrue = true;
String filename = "";
Iterator<?> iter1 = fileItr.iterator();
while (iter1.hasNext()) {
FileItem f = (FileItem) iter1.next();
if (!f.isFormField()) {
//详情 name=abc.png, size=376507 bytes, isFormField=false, FieldName=picture1
filename = f.getName() == null ? "" : f.getName();
filename = JiveGlobe.getFromRom()+".jpg";
File saveFile = new File(path, filename);
if (saveFile.exists()) {
isTrue = false;break;}
f.write(saveFile);
}
}
if(JiveGlobe.isEmpty(filename)){
returnObject =ResultPackaging.dealJsonObject(ConstantsCode.RESULT_CODE_FAIL, ConstantsCode.CODE_LACK_PARAMETER, null);
return returnObject;
}
returnObject =ResultPackaging.dealJsonObject(ConstantsCode.RESULT_CODE_SUCCESS, ConstantsCode.RESULT_CODE_SUCCESS, null);
//保存文件信息
UserInfo rd = new UserInfo();
rd.setSpareField1("1");
rd.setSpareField3(filename);
rd.setOpenId(openid);
userInfoMapper.updateByPrimaryKey(rd);
} catch (Exception e) {
System.out.println(e);
logger.error("###认证失败"+e);
}
return returnObject;
} }

2、MultipartFile

   

@RequestMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
System.out.println("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传的后缀名为:" + suffixName);
// 文件上传后的路径
String filePath = "D://";
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
/**
* 多文件具体上传时间,主要是使用了MultipartHttpServletRequest和MultipartFile
*
* @param request
* @return
*/
@RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload1(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
String filePath = "D://";
MultipartFile file = null; for (int i = 0; i < files.size(); ++i) {
file = files.get(i);
// 获取文件名
String fileName = file.getOriginalFilename();
System.out.println("上传的文件名为:" + fileName); if (!file.isEmpty()) {
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (Exception e) {
return "上传失败 " + i + " => " + e.getMessage();
}
} else {
return "上传失败 " + i + " 文件为空.";
}
}
return "上传成功";
}

3、CommonsMultipartResolver

  

*
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/uploadFile")
    public Map<String, Object> uploadFile(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        // 检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                try {
                    if (file != null && StringUtils.isNotBlank(file.getOriginalFilename().trim())) {
                        Map<String, String> metas = new HashMap<String, String>();
                        // 取得文件后缀
                        String filename = file.getOriginalFilename();
                        String newFileName = System.currentTimeMillis() + (int) (Math.random() * 100)
                                + filename.substring(filename.lastIndexOf("."));
                        metas.put(StorageConstants.META_KEY_FILENAME, newFileName);
                        String imgUrl = storageService.store(file.getBytes(), metas);
                        map.put("imgUrl", imgUrl);
                        map.put("retCode", "success");
                        // map.put("imgUrl",
                        // "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=611483611,2895064642&fm=117&gp=0.jpg");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            map.put("retCode", "error");
        }
        return map;

上一篇:每天一个Linux命令(2):cd


下一篇:Java添加事件的四种方式