javaweb中的文件上傳的一般寫法(初次接觸時寫)


javaweb上傳文件

上傳文件的jsp中的部分

上傳文件同樣可以使用form表單向后端發請求,也可以使用 ajax向后端發請求
	1. 通過form表單向后端發送請求
		 <form id="postForm" action="${pageContext.request.contextPath}/UploadServlet" method="post" enctype="multipart/form-data">
		    <div class="bbxx wrap">
				<input type="text" id="side-profile-name" name="username" class="form-control">
	    		<input type="file" id="example-file-input" name="avatar">
 				<button type="submit" class="btn btn-effect-ripple btn-primary">Save</button>
    		</div>
	    </form>			

	2. 通過ajax向后端發送請求
		1.
			$.ajax({  
    			 url : "${pageContext.request.contextPath}/UploadServlet",  
     			 type : "POST",  
			     data : $( '#postForm').serialize(),  
			     success : function(data) {  
			          $( '#serverResponse').html(data);  
			     },  
			     error : function(data) {  
			          $( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText);  
			     }  
			});  
			
		2. 
			var form = new FormData();
  			form.append("username","zxj");
			form.append("avatar",file);
			//var form = new FormData($("#postForm")[0]);
		 	$.ajax({
                url:"${pageContext.request.contextPath}/UploadServlet",
                type:"post",
                data:form,
                processData:false,
                contentType:false,
                success:function(data){
          
                    console.log(data);
                }
			});

java部分

/**
 * 上傳文件的servlet
 */
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChangeProfileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//上傳文件
			try {
//				request.getParameter("");					//創建磁盤文件工廠
				DiskFileItemFactory fileItemFactory =  new DiskFileItemFactory();
				//創建磁盤文件項
				ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
//				fileUpload.setHeaderEncoding("utf-8");
				fileUpload.setHeaderEncoding("UTF-8");// 解決中文文件名上傳亂碼.
				//解析上傳項
				List<FileItem> list = fileUpload.parseRequest(request);
				Map<String,String> map = new HashMap<String,String>();
				String fileName = null;
				for (FileItem fileItem : list) {
					if(fileItem.isFormField()){
						//如果是表單項
						String name = fileItem.getFieldName();
						String string = fileItem.getString("utf-8");
						//表單項的集合
						map.put(name, string);
					}else{
						//上傳項
						fileName = fileItem.getName();
						InputStream is = fileItem.getInputStream();
						// 獲得文件要上傳的路徑(后面的路徑可以自定義):
						String path = this.getServletContext().getRealPath("/back/imgs");
						OutputStream os = new FileOutputStream(path+"/"+fileName);//cs.jpg
						byte[] byts = new byte[1024];
						int len = 0;
						while ( (len = is.read(byts)) != -1 ) {
							os.write(byts, 0, len);
							os.flush();
						}
//						IOUtils.copy(is, os);
						is.close();
						os.close();
					}
				}
				
//				BeanUtils.populate();  	//將實體對應的屬性賦給實體(收集數據)
				if (!fileName.equals(null)&&!fileName.equals("")) {
					//將圖片路徑賦給實體的某個屬性					
				}
			//將實體的數據寫入到數據庫
		}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
}

注:
1. 上面的java部分的代碼可以直接使用,只需要將上傳的圖片路徑及收集數據並將數據寫入到數據庫即可
2. 上面上傳文件使用到了字節流,其實還可以使用別的流,這個需要讀者自己在下面完善測試
3. BeanUtils是一個工具 便於將實體對應的屬性賦給實體
4. 上傳文件不能使用 request.getParameter("")獲取參數了,而是直接將request解析,通過判斷每一項是文件還是非文件,然后進行相應的操作(文件的話就是用流來讀取,非文件的話,暫時保存到一個map中。)

本文是結合教師所講內容結合自己的理解總結所得,如需轉載請注明:http://www.cnblogs.com/zhuchenglin/p/8098015.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM