首页 技术 正文
技术 2022年11月8日
0 收藏 653 点赞 1,402 浏览 3948 个字

上传一个单文件,用request.getFile得到文件(下面的功能是上传到阿里云)

   @RequestMapping(value = {"/content"}, method = RequestMethod.POST, headers = "content-type=multipart/form-data")
public String content(ModelMap modelMap,
MultipartHttpServletRequest request,
HttpServletResponse response){
response.setHeader("Access-Control-Allow-Origin", "*");
OSSUpload ossUpload = new OSSUpload("xinmeiti");
Iterator<String> itr = request.getFileNames();
MultipartFile file = request.getFile(itr.next());
Map<String, Object> map = new HashMap<>();
try{
byte[] bytes = org.apache.poi.util.IOUtils.toByteArray(file.getInputStream());
String fileType = getImageType(bytes);
String md5 = StringUtils.md5(String.valueOf(bytes));
String fileName = firstName +"/"+md5 + "."+ fileType;
Map<String, Object> uploadResult = ossUpload.upload(bytes, fileName);
if(!uploadResult.get("status").equals(0)){
modelMap.addAttribute("json", StringUtils.toJson(uploadResult));
}else{
map.put("url", cndName+fileName);
modelMap.addAttribute("json", StringUtils.toJson(map));
}
} catch (IOException e) {
modelMap.addAttribute("json", StringUtils.toJson(new ReturnMap(10004, "上传图片失败")));
e.printStackTrace();
}
return "mis/json";
}

上传多个文件,用request.getFile得到多文件

 @RequestMapping(value = {"multipleFileUpload"}, method =  {RequestMethod.GET, RequestMethod.POST})
public String multipleFileUpload(
ModelMap modelMap,
MultipartHttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "type") String type,
@RequestParam(value = "jobId") String jobId) throws IOException {
List < MultipartFile > files = request.getFiles("files");
response.setHeader("Access-Control-Allow-Origin", "https://img.zhankr.net/lehyopdsue546397.gifmiao.com");
Map<String, Object> statusMap = new HashMap<>();
HttpSession session = request.getSession();
session.setAttribute("gifCompressStatus", statusMap);
int compressSize = getCompressSizeByValue(type);
for(MultipartFile file :files){
String filename = file.getOriginalFilename().split(".gif")[0];
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("size" , 0);
resultMap.put("status" , 0);
resultMap.put("url" , "");
statusMap.put(filename, resultMap);
InputStream is = file.getInputStream();
byte[] bytes = IOUtils.toByteArray(is);
CompressWorker worker = new CompressWorker(statusMap, bytes, filename, compressSize, jobId);
worker.start();
}
modelMap.addAttribute("json", StringUtils.toInsensitiveJson(new ReturnMap("线程已启动")));
return "json";
}
在使用MultipartHttpServletRequest类型的时候需要注意,随便什么request都是MultipartHttpServletRequest
在这里举两个可以用MultipartHttpServletRequest的例子。
后端代码:上传一个单文件
 @RequestMapping(value = "/uploadInsight", method = RequestMethod.POST)
public String uploadInsight(ModelMap modelMap,
MultipartHttpServletRequest request,
@RequestParam(value = "category") String category,
@RequestParam(value = "title") String title,
) throws IOException{
Iterator<String> itr = request.getFileNames();
MultipartFile file = request.getFile(itr.next());
Map<String, Object> map = uploadImage(file);
if(!map.get("state").equals("SUCCESS")){
modelMap.addAttribute("json", StringUtils.toJson(new ReturnMap(10004, "上传图片失败")));
return "mis/json";
}
String fengmianImgUrl = (String) map.get("name");
InsightModel insightModel = new InsightModel();
insightModel.setCategory(category);
insightModel.setThumbnail(fengmianImgUrl);
insightModel.setTitle(title);
datastore.save(insightModel);
modelMap.addAttribute("json", StringUtils.toJson((new ReturnMap("OK"))));
return "mis/json";
}
对应的前端代码可以是这样:(原生的js)
function upload(user){            //user是从表单里面接到的数据
var formData = new FormData();
formData.append("title", user.title);
formData.append("file", user.file);
formData.append("category", user.category);
var xhr = new XMLHttpRequest();
xhr.open('POST', "/editor/uploadInsight");
//xhr.withCredentials = true; //这个是关于跨域证书的
xhr.onload = function(){
if(xhr.readyState == 4 && xhr.status == 200){
            console.log("成功")
}
};
xhr.send(formData);
}

对应的前端代码也可以是这样:(jquery方式调用)

   var formData = new FormData();
formData.append("file", file);
formData.append("title", title);
formData.append("category", category); $.ajax({
type : "POST",
url : "/editor/uploadInsight",
data : formData,
processData : false,
contentType : false ,
file:file,
error: function(data) { },
success: function(data) { },
xhr: function() { }
});


    					
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,565
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,413
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,186
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905