java uses fileupload to receive uploaded files

The required packages are:


java service receiver:

method one)

//Upload the image to the server and get the url
	@RequestMapping("GetPortraitUrl")
	public @ResponseBody
	GetPortraitUrlResponse GetPortraitUrl(HttpServletRequest request) throws Exception{
		String uploadPath = "f:\\temp"; // directory to upload files
		String tempPath = "f:\\temp\\buffer\\"; //Temporary file directory
		File uploadFile = new File(uploadPath);
		if (!uploadFile.exists()) {
			uploadFile.mkdirs();
		}
		File tempPathFile= new File(tempPath);
		if (!tempPathFile.exists()) {
			tempPathFile.mkdirs();
		}
		System.out.println(request.getContentType());
		GetPortraitUrlResponse rResponse = new GetPortraitUrlResponse ();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		factory.setSizeThreshold(4096); // Set the buffer size, here is 4kb
		factory.setRepository(tempPathFile);// Set the buffer directory
		upload.setSizeMax(4194304); // Set the maximum file size, here is 4MB
		try {
			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> i = items.iterator();
			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				String fileName = fi.getName();
				if (fileName != null) {
					File fullFile = new File(fi.getName());
					File savedFile = new File(uploadPath, fullFile.getName());
					fi.write(savedFile);
				}
			}
		} catch (org.apache.commons.fileupload.FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}// Get all files
		return rResponse;	
	}
Method Two)

//upload picture
		@RequestMapping("GetPortraitUrl")
	    public void receiveData(HttpServletRequest request, HttpServletResponse response){  
	        
            PrintWriter out = null;  
            response.setContentType("text/html;charset=UTF-8");  
              
            Map map = new HashMap();  
            FileItemFactory factory = new DiskFileItemFactory();  
            ServletFileUpload upload = new ServletFileUpload(factory);  
            File directory = null;    
            List<FileItem> items = new ArrayList();  
            try {  
                items = upload.parseRequest(request);  
                // get all files  
                Iterator<FileItem> it = items.iterator();  
                while (it.hasNext()) {  
                    FileItem fItem = (FileItem) it.next();  
                    String fName = "";  
                    Object fValue = null;  
                    if (fItem.isFormField()) { // value of normal text field  
                        fName = fItem.getFieldName();  
    //                  fValue = fItem.getString();  
                        fValue = fItem.getString("UTF-8");  
                        map.put(fName, fValue);  
                    } else { // Get the value of the uploaded file  
                        fName = fItem.getFieldName();  
                        fValue = fItem.getInputStream();  
                        map.put(fName, fValue);  
                        String name = fItem.getName();  
                        if(name != null && !("".equals(name))) {  
                            name = name.substring(name.lastIndexOf(File.separator) + 1);  
                              
    //                      String stamp = StringUtils.getFormattedCurrDateNumberString();  
                      
                            directory = new File("f://test");    
                                 directory.mkdirs();  
                              
                            String filePath = ("f://test")+ File.separator + name;  
                            map.put(fName + "FilePath", filePath);  
                              
                            InputStream is = fItem.getInputStream();  
                            FileOutputStream fos = new FileOutputStream(filePath);  
                            byte[] buffer = new byte[1024];  
                            while (is.read(buffer) > 0) {  
                                fos.write(buffer, 0, buffer.length);  
                            }  
                            fos.flush();  
                            fos.close();  
                            map.put(fName + "FileName", name);  
                        }  
                    }  
                }  
            } catch (Exception e) {  
                System.out.println("Error reading http request attribute value!");  
    // e.printStackTrace ();  
            }  
              
            // data processing  
              
              
              
              
            try {  
                out = response.getWriter();  
                out.print("{success:true, msg:'Received successfully'}");  
                out.close();  
            } catch (IOException e) {  
                e.printStackTrace ();  
            }  
      
      
        }  



update.jsp file:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" isELIgnored="false"%>
      <%
    String appContext= request.getContextPath();// Get the root path of the current application
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() + appContext+"/" ;
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Upload Directory</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="GetPortraitUrl" name="uploadForm">
  Select a file: <input type="file" name="upfile"><br/>
  <br/>
  <input type="submit" value="上传">
</form>
</body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325750139&siteId=291194637