Java upload pictures to the server

In comparison colorful rich website or business logic programming process, will be a lot, especially when uploading pictures related to the operation of the picture. Not completely get rid of the paper work may need to upload the file backup paper, construction sites may require users to upload avatar, picture description and so on, which are required to upload pictures to the Internet from the local (server). The following describes the pit today I was doing pictures uploaded encountered in the course of ~

First, business description

  When business requirements will continue to produce machines in photos uploaded online in order to be able to see on the site.

Second, Solutions

  Because this piece of the picture processing has been relatively unfamiliar, little by little, so we plan to address these business needs. First, business broken down into the following sections:

  (1) server receives the browser to upload pictures. It is better to implement because most are server-side development based on B / S architecture, which is the logic and the browser for development.

  (2) server receives the client to upload pictures. This may seem too difficult, but how to properly send out the data is indeed a bit difficult, it is also the author stepped pit place today.

  (3) optimize the sound business logic.

Third, the server receives the browser to upload pictures

  1, the new page

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

    2, layer coding Controller

. 1  @Controller
 2  public  class UploadController {
 . 3  
. 4      @RequestMapping (value = "/ Upload", Method = RequestMethod.POST)
 . 5      @ResponseBody
 . 6      public String uploadImg (@RequestParam ( "IMG" ) a MultipartFile IMG, the HttpServletRequest Request, the HttpServletResponse Response) {
 . 7          String contentType = img.getContentType ();     // Get the type of file 
. 8          System.out.println ( "file type is:" +   contentType);
 . 9          String OriginalFilename img.getOriginalFilename = ();      // get the file of the original name
 10          //Whether the file is empty 
. 11          IF (! Img.isEmpty ()) {
 12 is              File targetImg = new new File ( "F.: / IMG" );
 13 is              // determines whether there is a folder 
14              IF (! TargetImg.exists ()) {
 15                  targetImg.mkdirs ();     // cascade create a folder 
16              }
 . 17              the try {
 18 is                  // start saving images 
. 19                  a FileOutputStream the outputStream = new new a FileOutputStream ( "F.: / IMG /" + OriginalFilename);
 20 is                  OutputStream.write (IMG. the getBytes ());
 21 is                 outputStream.flush();
22                 outputStream.close();
23             } catch (IOException e) {
24                 e.printStackTrace();
25             }
26         }
27         return "SUCCESS";
28     }
29 }
View Code

   3, Spring and dependent modifications (pits)

1 <!-- 文件上传组件 -->
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 <the bean ID = "the MultipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver">
 . 3       <! - Request encoding format ->
 . 4       <Property name = "defaultEncoding" value = "UTF-. 8"> </ Property>
 . 5       <- upload file size! (unit: bytes) ->
 . 6       <Property name = "maxUploadSize" value = "50000000"> </ Property >
 7       <- buffer size! (unit: KB) ->
 . 8       <Property name = "maxInMemorySize" value = "1024"> </ Property>
 . 9 </ the bean>
View Code

  4, start the project, open the web browser displays the corresponding picture upload, select the image, click Upload, you should see just upload the picture on the outside of the local path if not.

Fourth, the server receives the client upload pictures

  There are many online content about this section describes the use HttpURLConnection are uploading, this one is more complicated methods, need to manually package request, eloquent dozens of lines of code; the second is if the project is complex, then use the Session or Cookie, it is really no way out ~

  For these reasons, we choose to use HttpClient local image upload

  1, the introduction of related 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 a 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 staticUploadImage String (String path, base64String String, String ImageFilePath) throws ClientProtocolException, IOException {
 33 is          // 1. Create upload required element type
 34          // file loaded local 1.1 Photo 
35          File imageFile = new new File (ImageFilePath);
 36          FileBody = imageFileBody new new FileBody (imageFile);
 37 [          // 1.2 after loading data base64 encoded picture
 38 is  //         String imageBase64Data = base64String;
 39  //         byteArrayBody byteArrayBody = null;
 40  //         IF (StringUtils.isNotEmpty (imageBase64Data)) {
 41 is //             byte [] = byteImage Base64.decodeBase64 (imageBase64Data);
 42 is  //             byteArrayBody = new new ByteArrayBody (byteImage, "image_name");
 43 is  //         }
 44 is          // objects uploaded string loaded 1.3 
45          StringBody name = new new StringBody ( "ADMIN" , ContentType.TEXT_PLAIN);
 46 is          // 2. all the elements need to upload objects packaged into HttpEntity
 47  //         HttpEntity reqEntity = MultipartEntityBuilder.create () addPart ( "name", name) .addPart ( "IMG",. imageFileBody) .addPart ( "file2", byteArrayBody) .build (); 
48         ReqEntity = MultipartEntityBuilder.create the HttpEntity () addPart ( "name", name) .addPart ( "IMG." , ImageFileBody) .build ();
 49          // 3. Create HttpPost objects, for transmitting information comprising message post 
50          HttpPost HttpPost = new new HttpPost (path);
 51 is          httpPost.setEntity (reqEntity);
 52 is          // 4. HttpClient create objects, incoming network requests transmission operation performed in httpPost 
53 is          CloseableHttpClient httpClient = HttpClients.createDefault ();
 54 is          CloseableHttpResponse Response = httpClient.execute (HttpPost);
 55          // 5. the solid content acquisition and parse the contents of the returned object 
56 is          the 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("响应内容为:" + 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, no accident, then be able to see because of the exciting "SUCCESS" output in the console

Fifth, improve the business logic optimization

  1, because the picture is constantly generated, so you want to continue to upload pictures, upload the picture and guarantee of non-repetition.

 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 (STR String: List) {
 . 11              // No pictures marked for upload 
12 is              IF (str.startsWith ( "the Upload"! )) {
 13 is                  uploadImage (URL, "Chao", the basePath + STR); // Photo 
14                  new new File (the basePath + STR) .renameTo ( new new File (the basePath + "Upload_" + STR));     // rename images 
15              }
 16          }
 . 17          the Thread.sleep (1000 * 60);     // wait 60 seconds 
18      }
 19 }
View Code

  2, the server's perfect

  If you want to be able to browse images in web development in general, business is relatively small, then Tomcat is directly transmitted to the server, then the path will be recorded and written to the database; relatively large business can now set up a local image server, Nginx or other technical uses all can be done, then this also needs to be saved into the database path.

Guess you like

Origin www.cnblogs.com/yiychao/p/11790047.html