关于Springboot+bootstraps的文件上传和解析xml(一)

自己最先做了一个小Demo

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>uploadimg.html</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/dim/testUploading">
    <input type="file" name="file"/>
    <input class="uploadBtn" type="submit" value="上传"/>
</form>
</body>
</html>

controller:

@Controller
@RequestMapping("/dim")
public class UploadingController {

    //跳转到上传文件的页面
    @GetMapping("/uploading")
    @RequiresPermissions("dim:uploading:uploading")
    //@RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
    public String goUploadImg() {
        return "dim/uploading/uploading";
    }

    //处理文件上传
    @RequestMapping(value="/testUploading", method = RequestMethod.POST)
    public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,
                     HttpServletRequest request) {
        //String contentType = file.getContentType();
        //得到上传时的文件名
        String fileName = file.getOriginalFilename();
        //String filePath = request.getSession().getServletContext().getRealPath("test/");
        String filePath = "E:\\Program\\phm\\documents\\test\\" ;
        try {
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);
        } catch (Exception e) {
        }
            return "uploading,success";
    }
}

工具类:

public class FileUtil {

  public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
    File targetFile = new File(filePath);
    if (!targetFile.exists()) {
      targetFile.mkdirs();
    }
    FileOutputStream out = new FileOutputStream(filePath + fileName);
    out.write(file);
    out.flush();
    out.close();
  }

  public static boolean deleteFile(String fileName) {
    File file = new File(fileName);
    // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
    if (file.exists() && file.isFile()) {
      if (file.delete()) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }

  public static String renameToUUID(String fileName) {
    return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
  }
}

猜你喜欢

转载自blog.csdn.net/Dime_w/article/details/80082627
今日推荐