java Web 文件上传
生活随笔
收集整理的這篇文章主要介紹了
java Web 文件上传
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
注意:請求實體過大的問題,請修改Nginx服務器的大小(百度參考413 Request Entity Too Large 的解決方法)
jsp:<input type="file" ?style="height: 114px;width: 100%;position: absolute;opacity: 0;" name="file1" id="file1" >
java后臺部分:
1 @RequestMapping(value = "/uploadImage", method = RequestMethod.POST) 2 @ResponseBody 3 public String uploadImage(HttpServletRequest request) throws IOException { 4 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request; 5 Iterator<String> iterator = multipartRequest.getFileNames(); 6 String fileName = ""; 7 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); 8 String dir = "upload/" + sdf.format(new Date()) + "/"; 9 String realPath = request.getSession().getServletContext().getRealPath("/"); 10 while(iterator.hasNext()){ 11 MultipartFile multipartFile = multipartRequest.getFile(iterator.next()); 12 if(multipartFile != null){ 13 String fn = multipartFile.getOriginalFilename(); 14 String suffix = fn.substring(fn.lastIndexOf(".")); 15 fileName = dir + Utils.getRandomStringByLength(6) + suffix; 16 String path = realPath + fileName; 17 path = path.replace("\\", "/"); 18 File f = new File(path); 19 if(!f.mkdirs()){ 20 f.mkdir(); 21 } 22 multipartFile.transferTo(f); 23 } 24 } 25 return fileName; 26 } 27 // 上面方法需要用到下面的方法 28 public String getRandomStringByLength(int length) { 29 String base = "abcdefghijklmnopqrstuvwxyz0123456789"; 30 Random random = new Random(); 31 StringBuffer sb = new StringBuffer(); 32 for (int i = 0; i < length; i++) { 33 int number = random.nextInt(base.length()); 34 sb.append(base.charAt(number)); 35 } 36 return sb.toString(); 37 }?
轉載于:https://www.cnblogs.com/dwb91/p/6699110.html
總結
以上是生活随笔為你收集整理的java Web 文件上传的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: # c++运算符重载之 前置++, 后置
- 下一篇: 常见的java异常——java.lang