Java uploads pictures to the server

Keywords: Java Apache Database Spring

In the process of designing colorful websites or programs with rich business logic, there must be many related operations of pictures, especially the uploading of pictures. The paper office may need to backup and upload the paper documents, the website construction may need to upload the user's Avatar, picture description and so on, all of which need to upload the pictures from the local to the Internet (server). Next, I will introduce the pit I met in the process of uploading pictures today~

I. business description

When required by the business, the machine will be uploaded on the website with the photos produced continuously, so that it can be viewed on the website.

II. Solutions

As the processing of the picture is relatively new, we plan to solve these business requirements bit by bit. First, the business is divided into the following parts:

(1) the server receives the pictures uploaded by the browser. This is easy to implement, because most of the server-side development is based on B/S architecture, that is, logic and browser-side development.

(2) the server receives the pictures uploaded by the client. This may not seem difficult, but how to send the data correctly is a little difficult, which is where the author stepped on the pit today.

(3) optimization and improvement of business logic.

III. The server receives the pictures uploaded by the browser

1. Create a new web page

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Picture upload</title>
 6 </head>
 7 <body>
 8     <form action="/plant/upload.action" enctype="multipart/form-data"
 9         method="post">
10         Photo:<input type="file" name="img"/> <br/>
11         <input type="submit" value="upload"/>
12     </form>
13 </body>
14 </html>
view code

2. Code the Controller layer

 1 @Controller
 2 public class UploadController {
 3 
 4     @RequestMapping(value="/upload",method=RequestMethod.POST)
 5     @ResponseBody
 6     public String uploadImg(@RequestParam("img") MultipartFile img, HttpServletRequest request,HttpServletResponse response) {
 7         String contentType = img.getContentType();    // Get the type of file
 8         System.out.println("The file type is:" +  contentType);
 9         String originalFilename = img.getOriginalFilename();     // Get the original name of the file
10         // Judge whether the file is empty
11         if(!img.isEmpty()) {
12             File targetImg = new File("F:/img");
13             // Determine whether the folder exists
14             if(!targetImg.exists()) {
15                 targetImg.mkdirs();    //Cascade create folder
16             }
17             try {
18                 // Start saving pictures
19                 FileOutputStream outputStream = new FileOutputStream("F:/img/" + originalFilename);
20                 outputStream.write(img.getBytes());
21                 outputStream.flush();
22                 outputStream.close();
23             } catch (IOException e) {
24                 e.printStackTrace();
25             }
26         }
27         return "SUCCESS";
28     }
29 }
view code

3. Spring and dependency modification (small pit)

1 <!-- File upload component -->
2 <dependency>
3     <groupId>commons-fileupload</groupId>
4     <artifactId>commons-fileupload</artifactId>
5     <version>${commons-fileupload.version}</version>
6 </dependency>
view code
1 <!-- Support file upload -->
2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
3      <!-- Request encoding format -->
4      <property name="defaultEncoding" value="utf-8"></property>
5      <!-- Upload file size(Company:byte) -->
6      <property name="maxUploadSize" value="50000000"></property>
7      <!-- Buffer size(Company:KB) -->
8      <property name="maxInMemorySize" value="1024"></property>
9 </bean>
view code

4. Start the project, open the browser to display the corresponding image uploaded web page, select the image, and click upload. If you do not go out of the local path, you should see the image just uploaded.

IV. the server receives the pictures uploaded by the client

There are a lot of contents on the Internet. This part introduces the use of HttpURLConnection for uploading. The first method is relatively complex. You need to manually encapsulate the request and spread dozens of lines of code. The second is that if the project is relatively complex and uses Session or Cookie, there is no way~

Based on the above reasons, this paper chooses to use HttpClient to upload local pictures

1. Introduce relevant dependencies

 1 <dependency>
 2     <groupId>org.apache.httpcomponents</groupId>
 3     <artifactId>httpclient</artifactId>
 4     <version>4.5.3</version>
 5 </dependency>
 6 <dependency>
 7     <groupId>org.apache.httpcomponents</groupId>
 8     <artifactId>httpmime</artifactId>
 9     <version>4.5.3</version>
10 </dependency>
view code

2. Write client program

 1 import java.io.BufferedReader;
 2 import java.io.File;
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.io.InputStreamReader;
 6 import java.util.Arrays;
 7 
 8 import org.apache.commons.codec.binary.Base64;
 9 import org.apache.commons.lang3.StringUtils;
10 import org.apache.http.HttpEntity;
11 import org.apache.http.client.ClientProtocolException;
12 import org.apache.http.client.methods.CloseableHttpResponse;
13 import org.apache.http.client.methods.HttpPost;
14 import org.apache.http.entity.ContentType;
15 import org.apache.http.entity.mime.MultipartEntityBuilder;
16 import org.apache.http.entity.mime.content.ByteArrayBody;
17 import org.apache.http.entity.mime.content.FileBody;
18 import org.apache.http.entity.mime.content.StringBody;
19 import org.apache.http.impl.client.CloseableHttpClient;
20 import org.apache.http.impl.client.HttpClients;
21 import org.apache.http.util.EntityUtils;
22 
23 public class ClientUpload {
24 
25     public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException {
26         String url = "http://localhost:8090/plant/upload.action";
27 //        String basePath = "F:\\img\\";
28         String path = "G:\\123.jpg";
29         uploadImage(url, "dfsdfsdfsdf",path);
30     }
31 
32     public static String uploadImage(String path, String base64String, String imageFilePath) throws ClientProtocolException, IOException {
33         // 1. Create element type required for upload
34         // 1.1 Loading files for locally uploaded pictures
35         File imageFile = new File(imageFilePath);
36         FileBody imageFileBody = new FileBody(imageFile);
37         // 1.2 Loading process base64 Encoded picture data
38 //        String imageBase64Data = base64String;
39 //        ByteArrayBody byteArrayBody = null;
40 //        if (StringUtils.isNotEmpty(imageBase64Data)) {
41 //            byte[] byteImage = Base64.decodeBase64(imageBase64Data);
42 //            byteArrayBody = new ByteArrayBody(byteImage, "image_name");
43 //        }
44         // 1.3 Load object for upload string
45         StringBody name = new StringBody("admin", ContentType.TEXT_PLAIN);
46         // 2. Package all elements to be uploaded into HttpEntity object
47 //        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("name", name).addPart("img", imageFileBody).addPart("file2", byteArrayBody).build();
48         HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("name", name).addPart("img", imageFileBody).build();
49         // 3. Establish HttpPost Object to include information transmission post news
50         HttpPost httpPost = new HttpPost(path);
51         httpPost.setEntity(reqEntity);
52         // 4. Establish HttpClient Objects, passing in httpPost Perform the action of sending network request
53         CloseableHttpClient httpClient = HttpClients.createDefault();
54         CloseableHttpResponse response = httpClient.execute(httpPost);
55         // 5. Get the returned entity content object and parse the content
56         HttpEntity resultEntity = response.getEntity();
57         String responseMessage = "";
58         try {
59             if (resultEntity != null) {
60                 InputStream is = resultEntity.getContent();
61                 BufferedReader br = new BufferedReader(new InputStreamReader(is));
62                 StringBuffer sb = new StringBuffer();
63                 String line = "";
64                 while ((line = br.readLine()) != null) {
65                     sb.append(line);
66                 }
67                 responseMessage = sb.toString();
68                 System.out.println("The response content is:" + responseMessage);
69             }
70             EntityUtils.consume(resultEntity);
71         } finally {
72             if (null != response) {
73                 response.close();
74             }
75         }
76         return responseMessage;
77     }
78 }
view code

3. So far, if there is no accident, you should be able to see the exciting "SUCCESS" output on the console

V. optimization and improvement of business logic

1. Since the pictures are constantly generated, it is necessary to upload the pictures continuously and ensure that the uploaded pictures are not repeated.

 1 public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException {
 2     String url = "http://localhost:8090/plant/upload.action";
 3     String basePath = "F:\\img\\";
 4 //    String path = "G:\\123.jpg";
 5 //    uploadImage(url, "dfsdfsdfsdf",path);
 6     while (true) {
 7         File file = new File(basePath);
 8         String[] list = file.list();
 9         Arrays.sort(list);
10         for (String str : list) {
11             // Picture not marked for upload
12             if (!str.startsWith("Upload")) {
13                 uploadImage(url, "chao", basePath + str); // Upload pictures
14                 new File(basePath + str).renameTo(new File(basePath + "Upload_" + str));    // Rename picture
15             }
16         }
17         Thread.sleep(1000*60);    //Wait for 60 seconds.
18     }
19 }
view code

2. Improvement of the server

If you want to be able to browse the pictures in the developed website, if the general business is relatively small, you can directly send them to Tomcat server, and then record the path and write it into the database; if the business is relatively large, you can set up a picture server locally, which can be achieved by using Nginx or other technologies, and then you need to write the path into the database for saving.

Posted by l_evans on Sun, 03 Nov 2019 11:29:33 -0800