spring 上傳文件
阿新 • • 發佈:2017-07-18
eth tempfile ram pin size pri bean cat adc
1、配置文件部分
在spring的配置文件中加入下面代碼
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"/>
2、用到的jar包
commons-fileupload-1.2.1.jar commons-io-1.3.2.jar 3、代碼部分--上傳到本地文件夾public class UploadController { //設置文件的路徑 File filePath = new File("D:/workspace-letter"); @RequestMapping(value= "/upload", method = RequestMethod.POST) @ResponseBody //可以成功調取 public String upload(@RequestParam MultipartFile file) throws IOException { //獲取文件原始名稱 String filename = file.getOriginalFilename(); //獲取文件擴展名 String fileExtension = filename.substring(filename.lastIndexOf("."));//img 文件名前綴 File tempFile = File.createTempFile("img", fileExtension,filePath); try{ InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(tempFile); IOUtils.copy(in, out); }catch(Exception e){ e.printStackTrace(); }return filename; } }
4、上傳到服務器
@Controller public class UploadController { @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String upload(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException { //設置服務器的上傳路徑 File filePath = new File("//sharedata//p4"); String filename = file.getOriginalFilename(); String fileExtension = filename.substring(filename.lastIndexOf(".")); File tempFile = File.createTempFile("LETTER", fileExtension,filePath); try { InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(tempFile); IOUtils.copy(in, out); } catch (Exception e) { e.printStackTrace(); } return filePath.getPath() + "/" + filename; } }
spring 上傳文件