1.編碼實現文件上傳
jsp頁面
注意事項:類型是file的input一定要有name屬性
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>傳統文件上傳</h3>
<form action="user/fileupload1" method="post" enctype="multipart/form-data">
選擇文件:<input type="file" name="upload" /><br/>
<input type="submit" value="上傳" />
</form>
</body>
</html>
Controller
@RequestMapping("/fileupload1")
public String fileupload1(HttpServletRequest request) throws Exception {
System.out.println("文件上傳...");
// 使用fileupload組件完成文件上傳
// 上傳的位置
String path = request.getSession().getServletContext().getRealPath("/uploads/");
// 判斷,該路徑是否存在
File file = new File(path);
if(!file.exists()){
// 創建該文件夾
file.mkdirs();
}
// 解析request對象,獲取上傳文件項
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 解析request
List<FileItem> items = upload.parseRequest(request);
// 遍歷
for(FileItem item:items){
// 進行判斷,當前item對象是否是上傳文件項
if(item.isFormField()){
// 說明普通表單向
}else{
// 說明上傳文件項
// 獲取上傳文件的名稱
String filename = item.getName();
// 把文件的名稱設置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 完成文件上傳
item.write(new File(path,filename));
// 刪除臨時文件
item.delete();
}
}
return "success";
}
2.SpringMVC文件上傳
配置文件解析器
<!--配置文件解析器對象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上傳文件的最大大小,單位字節-->
<property name="maxUploadSize" value="10485760" />
</bean>
Controller
@RequestMapping("/fileUpLoad2")
public String fileUpLoad2(HttpServletRequest request, MultipartFile upload) throws Exception {
System.out.println("springMvc文件上傳...");
String path = request.getSession().getServletContext().getRealPath("/uploads/");
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
//獲取文件名
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid + "_" + filename;
//完成文件上傳
upload.transferTo(new File(path, filename));
return "success";
}
3.跨服務器上傳
部署兩個tomcat
Controller
@RequestMapping("/fileUpLoad3")
public String fileUpLoad3(MultipartFile upload) throws Exception {
System.out.println("跨服務器文件上傳...");
//上傳文件服務器路徑
String path = "http://localhost:9090/fileUpLoadService_war_exploded/uploads/";
//獲取文件名
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid + "_" + filename;
//創建客戶端對象
Client client = Client.create();
//和圖片服務器進行連接
WebResource webResource = client.resource(path + filename);
//上傳文件
webResource.put(upload.getBytes());
return "success";
}
常見錯誤及解決方法
403
tomcat服務器默認不可寫操作,只允許讀
解決方法:在tomcat的web.xml中添加如下代碼
409
409路徑錯誤,即當前訪問的路徑下沒有相關文件。
解決方法:在target/文件名文件夾下創建和服務器上傳路徑一致的文件夾