1. 程式人生 > >SpringMVC使用FileUpload進行檔案上傳

SpringMVC使用FileUpload進行檔案上傳

匯入FileUpload和common-io的Jar包

注意:1、Struts2需要使用其他方法:struts2過濾時,會改變reqeust的型別,由HttpServletRequest變成MultiPartRequestWrapper

1、Test.jsp:

<form action="<%=basePath%>self/testFileUpload.do" method="post" enctype="multipart/form-data">
    	<input type="text" name="num">
    	<input name="img1" type="file" accept="image/gif,image/jpg,image/png,image/jpeg"/>
    	<input name="img2" type="file" accept="image/gif,image/jpg,image/png,image/jpeg"/>
    	<input type="submit" name="test">
    	<input type="reset" name="test1">
    </form>

2、controller:
@RequestMapping(value="/testFileUpload")
	public void  testFileUpload(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String num = "";
		String img1 = "";
		String img2 = "";
		String fileName = "";
		try {
			String t = request.getCharacterEncoding();
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);//判斷是否是表單檔案型別
			if(isMultipart){
				DiskFileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding(request.getCharacterEncoding());//這裡很重要啊 解決linux環境下上傳檔名亂碼的問題
				//upload.setFileSizeMax(3*1024*1024);//3M
				List items = upload.parseRequest(request);
				if(items.size() == 0){
					System.out.println("無資料");
				}
				Iterator<Object> formItem = items.iterator();
				while(formItem.hasNext()){
					FileItem item = (FileItem) formItem.next();
					//如果是表單元素
					if(item.isFormField()){
						if (item.getFieldName().equals("num")) {
							num = item.getString(request.getCharacterEncoding()).trim();
						}
					}
					//如果不是表單元素
					if(!item.isFormField()){
						String name = item.getName();
						String type = item.getContentType();
						long sizeInBytes = item.getSize();
						
						try {
							String fullName = item.getName().trim();
							if(fullName != ""){
								fileName = System.currentTimeMillis() + fullName.substring(fullName.indexOf("."));
								if(item.getFieldName().equals("img1")){
									fileName = "img1-" + System.currentTimeMillis() + fullName.substring(fullName.indexOf("."));
								}
								if(item.getFieldName().equals("img2")){
									fileName = "img2-" + System.currentTimeMillis() + fullName.substring(fullName.indexOf("."));
								}
								String tomcatRoot = FileOperator.getRootPath();
								String path = tomcatRoot;
								if(FileOperator.FileUploadEx(path, fileName, item.getSize(), item.getInputStream())){
									if(item.getFieldName().equals("img1")){
										System.out.println("testimg1");
									}
									if(item.getFieldName().equals("img2")){
										System.out.println("testimg2");
									}
								}
							}
							
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}else{
				System.out.println("非multipart/form-data提交方式");
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}