上传一个单文件,用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", "http://www.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() { }
});

												

java,单文件和多文件上传代码范例的更多相关文章

  1. git通过diff文件,合并未上传代码库代码

    今天有段代码需要从别人的机器上同步到本地,但是这段代码还没上库,所以要么将这部分代码打包传过来,或者,用下面的办法. 由于代码修改涉及多个文件,打包搞过来确实比较麻烦,在网上找了下,发现可以用git ...

  2. 使用webstorm上传代码到github

    使用webstorm上传代码到github 字数681 阅读330 评论0 喜欢5 之前使用过webstorm上传代码到github,过了几个月竟然发现自己忘记了,好记性不如烂笔头啊,今天又重新用了一 ...

  3. 初次使用git上传代码到github远程仓库

    https://blog.csdn.net/loner_fang/article/details/80488385 2018年05月28日 21:02:31 蒲公英上的尘埃 阅读数:697 因为最近在 ...

  4. 使用git上传代码到github远程仓库

    一.新建代码库注册好github登录后,首先先在网页上新建代码库. 点击右上角"+"→New repository 进入如下页面:按照要求填写完成后,点击按钮创建代码库创建成功. ...

  5. [html5+java]文件异步读取及上传核心代码

    html5+java 文件异步读取及上传关键代码段 功能: 1.多文件文件拖拽上传,file input 多文件选择 2.html5 File Api 异步FormData,blob上传,图片显示 3 ...

  6. c# 模拟表单提交,post form 上传文件、大数据内容

    表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipart/form-data,而且要设定一个 boundary 参数,这个参数是由应用程序自行产生,它会用来识别每 ...

  7. django 基于form表单上传文件和基于ajax上传文件

    一.基于form表单上传文件 1.html里是有一个input type="file" 和 ‘submit’的标签 2.vies.py def fileupload(request ...

  8. c# 模拟表单提交,post form 上传文件、数据内容

    转自:https://www.cnblogs.com/DoNetCShap/p/10696277.html 表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipar ...

  9. SpringMVC上传压缩文件,解压文件,并检测上传文件中是否有index.html

    SpringMVC上传压缩文件,解压文件,并检测上传文件中是否有index.html 说明: 1.环境:SpringMVC+Spring+Tomcat7+JDK1.7 2.支持 zip和rar格式的压 ...

随机推荐

  1. ERROR 1130:mysql 1130连接错误的有效解决方法

    今天在用sqlyog连接非本地的Mysql服务器的数据库,居然无法连接很奇怪,报1130错误, ERROR 1130: Host 192.168.3.100 is not allowed to con ...

  2. Python记录-python执行shell命令

    # coding=UTF-8 import os def distcp(): nncheck = os.system('lsof -i:8020') dncheck = os.system('lsof ...

  3. 搭建Keepalived+LVS-DR集群

    (1).Keepalived概述 keepalived 是一个类似于 layer3, 4 & 5 交换机制的软件,也就是我们平时说的第 3 层.第 4 层和第 5层交换. Keepalived ...

  4. 报错:ModuleNotFoundError: No module named '_ctypes'

    报错背景: CentOS 7 Python3.7 安装 setuptools 插件的时候报错. 报错现象: [root@master setuptools-]# python3. setup.py b ...

  5. sed替换字符串(变量)

    sed “s/查找字段/替换字段/g” echo helloworld|sed  ‘s/hello/world/g’ sed 替换字符串以变量形式 1.sed命令使用双引号的情况下,可以使用$var( ...

  6. .Net MVC 标签页

    目录 Bootstrap的标签页 适合.Net MVC的标签页 Bootstrap的标签页 下面是Bootstrap的标签页,挺好的,但是用的id,内容是固定的?我不知道怎么变成不同的视图来 < ...

  7. 【Leetcode_easy】937. Reorder Log Files

    problem 937. Reorder Log Files solution: class Solution { public: vector<string> reorderLogFil ...

  8. Linux下Mongodb安装和启动配置 转载

    原文地址:https://www.cnblogs.com/Jimmy104/p/6181899.html 以下文章为转载,感谢网友,原文链接 http://blog.csdn.net/yuwenrul ...

  9. R Multiple Plots

    R Multiple Plots In this article, you will learn to use par() function to put multiple graphs in a s ...

  10. [转载]SQL Server提权系列

    本文原文地址:https://www.cnblogs.com/wintrysec/p/10875232.html 一.利用xp_cmdshell提权 xp_cmdshell默认是关闭的,可以通过下面的 ...