文件上傳實例(使用plupload)

1、UploaderServlet

	public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        Integer schunk = null;// 分割塊數
        Integer schunks = null;// 總分割數
        String name = null;// 文件名
        OutputStream outputStream = null;
        InputStream inputStream = null;
        PrintWriter pw = response.getWriter(); // 用於給前臺反饋數據
        String msg = "";
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(1024);
                factory.setRepository(new File(repositoryPath));// 設置臨時目錄
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setHeaderEncoding("UTF-8");
                upload.setSizeMax(5 * 1024 * 1024);// 設置附近大小
                List<FileItem> items = upload.parseRequest(request);
                // 生成新文件名
                String newFileName = null;
                for (FileItem item : items) {
                    if (!item.isFormField()) {// 如果是文件類型
                        name = item.getName();// 獲得文件名

                        // 第二次獲取的是fileContent
                        // 將文件流存入dataInfo
                        System.out.println("file size = " + item.getSize());
                        inputStream = item.getInputStream();// 將上傳的文件存入輸入流中
                        
                        newFileName = name;
                        if (name != null) {
                            String nFname = newFileName;
                            // 獲取擴展名
                            String postfix = newFileName.substring(nFname
                                    .lastIndexOf(".") + 1);
                            if (!"ini".equals(postfix) && !"txt".equals(postfix)) {
                                pw.println("上傳文件必須爲.ini或.txt文件!");
                                return;
                            }
                            if (schunk != null) {
                                nFname = schunk + "_" + name;
                            }
                            
                            // 將dataInfo存入數據庫
                            staLocationBO.saveBlob(dataInfo, inputStream);
                            System.out.println("文件寫入數據庫成功...");
                            // 寫入到本地文件中
                            /*File savedFile = new File(uploadPath, nFname);
                            item.write(savedFile);*/
                        }
                    } else { // 表單類型
                        // 判斷是否帶分割信息
                        // 第一次獲取的是hidden
                        
                        String dwdName = items.get(0).getFieldName();
                        // 根據fieldName(dwdName)進行查詢後存入StaLocation對象
                        dataInfo = staLocationBO.getDataById(dwdName);

                        if (item.getFieldName().equals("chunk")) {
                            schunk = Integer.parseInt(item.getString());
                        }
                        if (item.getFieldName().equals("chunks")) {
                            schunks = Integer.parseInt(item.getString());
                        }
                    }
                }

                
                // response.getWriter().write("{\"status\":true,\"newName\":\""+newFileName+"\"}");
                msg = "文件上傳成功!";
                pw.println(msg);
            } catch (FileUploadException e) {
                logger.error(e.getMessage());
                e.printStackTrace();
                msg = "文件上傳失敗,請重試!";
                pw.println(msg);
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
                msg = "文件上傳失敗,請重試!";
                pw.println(msg);
            } finally {
                if (outputStream != null){
                    outputStream.close();
                }
                if(inputStream != null){
                    inputStream.close();
                }
                if (pw != null) {
                    pw.close();
                }
            }
        }
    }

	@Override
	public void init(ServletConfig config) throws ServletException {
		repositoryPath = FileUtils.getTempDirectoryPath();
		
		uploadPath = config.getServletContext().getRealPath(config.getInitParameter("uploadPath")); //如果上傳到本地文件,在這裏設置路徑
		File up = new File(uploadPath);
		if(!up.exists()){
			up.mkdir();
		}
        }
 }

2、saveBlob方法

    public void saveBlob(StaLocation staLocation,InputStream inputStream) throws Exception{
        byte[] b = new byte[10240000];
        int length = 0;
        while ((length = inputStream.read(b)) != -1) {
            Blob fileContent = getSessionFactory().getCurrentSession().getLobHelper().createBlob(b);
            staLocation.setFileContent(fileContent);
        }
        getSessionFactory().getCurrentSession().saveOrUpdate(staLocation);
    }

3、jsp

<form id = "upLoadForm" method="post" enctype="multipart/form-data"> 
			<table class="csstable">
				<tr>
					<th align="center">
	                  <label>電務段名稱</label>
	                </th>
					<td>
						<span id="czmc"></span>
					</td>
					<th align="center">
	                  <a id = "aDownLoad" href ="">下載</a>
	                </th>
				</tr>
				
				<tr>
					<th align="center">
	                  <input type = "file" name = "file" value = "瀏覽"/>
	                </th>
					<th align="center">
	                  <input type="submit" id = "upLoadButton" value = "上傳" />
	                </th>
					
				</tr>
			</table>
		</form>

4、javascript

    $(document).ready(function () {
    	var ajax_option={
	        type : "post",
	        //url : "${pageContext.request.contextPath}/uploader",
	        url : "uploader",
	        dataType : "text",
	       // clearForm: true,
	        success : function(data) {
	            alert(data);
	        }
        };
        $('#upLoadForm').submit(function() { //當new_book這個form的submit事件被觸發之時
            //debugger;
            $(this).ajaxSubmit(ajax_option); //用ajaxSubmit這個方法將new_book表單的內容提交到後臺
            return false;
        });
    });
5、引入jquery-form.js文件

發佈了30 篇原創文章 · 獲贊 5 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章