zoukankan      html  css  js  c++  java
  • java,单文件和多文件上传代码范例

    上传一个单文件,用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() {
            
            }
        });




  • 相关阅读:
    c#调用dll,::CoInitialize(NULL)出错
    使用 Anthem.NET 的常见回调(Callback)处理方式小结
    主题和皮肤学习
    得到任意网页源代码 (利用WebClient和WebRequest类)
    HTML marquee标签详解
    制作一个简单的天气预报
    CSS中的类class和标识id选择符(.和#号)
    String split '.'
    Map 的 clear() 方法会清空 Map对象
    sqLite 执行查询语句时报错__及SimpleCursorAdapter
  • 原文地址:https://www.cnblogs.com/qianxinxu/p/6611377.html
Copyright © 2011-2022 走看看