Heim  >  Fragen und Antworten  >  Hauptteil

html5 - H5提交MIME类型为multipart/form-data类型的表单,后端如何处理(比如java,.NET)?

<form action="example.jsp" enctype="multipart/form-data" method="POST">
    <label for="fname">请选择</label>
    <input type="file" name="fname"/>
</form>
怪我咯怪我咯2712 Tage vor762

Antworte allen(3)Ich werde antworten

  • 迷茫

    迷茫2017-04-18 10:31:57

    /**
         * 上传图片接口,任务详情的插图和评论的插图都用
         * 
         * @param request
         * @param taskId
         * @param taskDiscussId
         * @return
         */
        @RequestMapping(value = "tasks/{taskId}/files", method = RequestMethod.POST)
        public Results<String> uploadFiles(HttpServletRequest request, @PathVariable Integer taskId,
                Integer taskDiscussId) {
            Results<String> r = new Results<String>();
            r.setCode(StatusCode.OK);
            try {
                // 上传图片处理
                CommonsMultipartResolver multipartResolver =
                        new CommonsMultipartResolver(request.getSession().getServletContext());
                if (!multipartResolver.isMultipart(request)) {
                    r.setCode(StatusCode.FAIL);
                    r.setMessage("没有接收到文件,请重新选择!");
                    return r;
                }
                // 将请求还原成文件上传请求
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                MultipartFile mf = multipartRequest.getFile("file");
    
                // 验证文件后缀是否正确
                if (!FileFormatUtil.checkFileFormat(mf.getOriginalFilename(), FileFormat.IMAGE)) {
                    HugeServerException.throwException("用户上传头像格式错误", StatusCode.USER_IMG_FOR_ERROR);
                }
                // 这里是上传文件,返回保存的路径
                String savePath = null;
                // 前台有传评论ID的话,那就是上传评论的插图(目前只有上传图片,无其他格式文件)
                if (taskDiscussId == null) {
                    savePath = UploadFileUtils.uploadFile(request, mf, ConfigParam.task_attach);
                    TaskFile file = new TaskFile();
                    file.setTaskId(taskId);
                    file.setFileType(FileType.IMAGE.getValue());
                    file.setFileName(mf.getName());
                    file.setFilePath(savePath);
                    taskFileService.insert(file);
                }
                else {
                    savePath = UploadFileUtils.uploadFile(request, mf, ConfigParam.task_discuss_attach);
                    TaskDiscussFile file = new TaskDiscussFile();
                    file.setTaskDiscussId(taskDiscussId);
                    file.setFileType(FileType.IMAGE.getValue());
                    file.setFileName(mf.getName());
                    file.setFilePath(savePath);
                    taskDiscussFileService.insert(file);
                }
                r.setData(savePath);
            }
            catch (Exception e) {
                log.error("File upload failed.", e);
                r.setCode(StatusCode.TASK_FILE_UPLOAD_FAIL);
                r.setMessage("任务文件上传失败!");
            }
            return r;
        }
    public class UploadFileUtils extends BaseFile{
        
        
        public static String getNewFileName(String suffix){
            if(StringUtils.isEmpty(suffix)){
               return null;
            }
            return new Date().getTime()+UNDERLINE+(new Random().nextInt(100000000)+1)+POINT+suffix;
        }
        
        
    
        public static String uploadFile(HttpServletRequest request,MultipartFile file, String fileSavePath) throws Exception{
            if(file == null){
                return "";
            }
            String originalFilename = file.getOriginalFilename();
            if(StringUtils.isBlank(originalFilename)){
                return "";
            }
            //boolean isr = FileFormatUtil.checkFileFormat(originalFilename, fileFormat);
            /*if(!isr){
                throw new HugeFileException("上传文件格式错误,请重试");
            }*/
            //物理路径
            String wlPath = getFullPath(request,fileSavePath);
            File f = new File(wlPath);
            if(!f.exists()){
                f.mkdirs();
            }
            //获取后缀名
            String suffix = FileUtils.getFileSuffix(originalFilename);
            //通过后缀名,获取新的一个文件名
            String newFileName = getNewFileName(suffix);
            wlPath = wlPath+SPRIT+newFileName;
            //这个参数是为了保存到数据库中的值
            String ljPath = fileSavePath +SPRIT+newFileName;
            //保存文件
            copy(file.getInputStream(), wlPath);
            //file.transferTo(new File(f.getAbsolutePath(),newFileName));
            return ljPath;
        }
        
    
        private static void copy(InputStream fis, String newPath) throws Exception{  
            FileOutputStream fos =null;
            try {
                fos = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];     
                int len = 0;     
                while ((len = fis.read(buffer)) > 0) {     
                    fos.write(buffer, 0, len);     
                }     
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("保存失败");
            }finally {
                 try {
                    fis.close();
                    fos.close(); 
                 } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    throw new Exception("保存失败");
                 }     
            }
           
        }
        
        
        public static String getFullPath(HttpServletRequest request,String filePath){
            return ConfigParam.path_absolute+filePath;
          //return request.getSession().getServletContext().getRealPath(fileConfig);
        }
        
    }
    

    Antwort
    0
  • 迷茫

    迷茫2017-04-18 10:31:57

    问题已解决 公司里用的.NET传文件的方式是用AJAX的POST方式提交,在url后面加相关参数,Request Payload中加文件的二进制流

    Antwort
    0
  • ringa_lee

    ringa_lee2017-04-18 10:31:57

    ASP.NET MVC

    [HttpPost]
    public ActionResult UploadImage(HttpPostedFileBase image){
        image.SaveAs(fileName);
    }
    

    ASP.NET Core

    
    [HttpPost]
    public IActionResult UploadImage(IFormFile image){
        image.Save(fileName);
    }

    Antwort
    0
  • StornierenAntwort