Springboot implementation File Upload

Source: Internet
Author: User
Tags getmessage

Using Springboot to implement the server, and then use Java and HTML5 implementation of the client upload test.

First, server-side interface program. For the convenience of controller in the written, formal procedures I like to put on the service layer for processing calls.

@RestController @RequestMapping ("/file") public class Filecontroller {/** * Single File Upload * * @param file * @param request * @return */@PostMapping ("/upload") @ResponseBody public String upload (@RequestPa RAM ("file") multipartfile file, HttpServletRequest request) {if (!file.isempty ()) {String Savefilena
            me = File.getoriginalfilename ();
            File SaveFile = new file (Request.getsession (). Getservletcontext (). Getrealpath ("/upload/") + Savefilename);
            if (!savefile.getparentfile (). exists ()) {Savefile.getparentfile (). Mkdirs ();
                try {bufferedoutputstream out = new Bufferedoutputstream (new FileOutputStream (SaveFile));
                Out.write (File.getbytes ());
                Out.flush ();
                Out.close ();
            Return Resultutils.buildresult (Savefile.getname () + "upload success");
                catch (FileNotFoundException e) {E.printstacktrace ();
            return Resultutils.buildresult ("Upload failed," + e.getmessage ());
                catch (IOException e) {e.printstacktrace ();
            return Resultutils.buildresult ("Upload failed," + e.getmessage ());
        else {return Resultutils.buildresult ("Upload failed because file is empty."); }/** * Multiple file Upload * * @param request * @return/@PostMapping ("/uploadfiles") @Re Sponsebody public String uploadfiles (HttpServletRequest request) throws IOException {file Savepath = new File
        (Request.getsession (). Getservletcontext (). Getrealpath ("/upload/"));
        if (!savepath.exists ()) {savepath.mkdirs ();
        } list<multipartfile> Files = ((multiparthttpservletrequest) request). GetFiles ("file");
        Multipartfile file = null;
        Bufferedoutputstream stream = null;
      for (int i = 0; i < files.size (); ++i) {file = Files.get (i);      if (!file.isempty ()) {try {byte[] bytes = File.getbytes ();
                    File SaveFile = new file (Savepath, File.getoriginalfilename ());
                    stream = new Bufferedoutputstream (new FileOutputStream (SaveFile));
                    Stream.Write (bytes);
                Stream.Close ();
                        The catch (Exception e) {if (stream!= null) {stream.close ();
                    stream = null;
                Return "First" + i + "File upload error" + e.getmessage ();
            } else {return "subclause" + i + "file is empty";
    } return "All files uploaded successfully"; }
}
However, files larger than 1MB will be prompted for errors when they are uploaded, so set them up. Adding a configuration file is ok.

@Configuration public
class Fileuploadconfig {

    @Bean public
    multipartconfigelement Multipartconfigelement () {
        Multipartconfigfactory factory = new Multipartconfigfactory ();
        Factory.setmaxfilesize ("100MB"); 
        Factory.setmaxrequestsize ("100MB");
        return Factory.createmultipartconfig ();
    }
You can also include these two sentences in application.properties:


SPRING.HTTP.MULTIPART.MAXFILESIZE=100MB
SPRING.HTTP.MULTIPART.MAXREQUESTSIZE=100MB

Choose one of the two.

2.java Client test program, the Android side is the same, I am using the RETROFIT2 framework, the following is a three-part code:

Interface:

Public interface Testservice {

    //File upload
    @Multipart
    @POST ("Upload")
    Call<netresult<object >> Upload (@Part multipartbody.part part);


API section:

public class Testapi extends Netapi {
    private static String Base_url = "http://192.168.1.101:8080/springbootdemo/ file/";
    private static Testservice service = Netclient.getretrofit (Base_url). Create (Testservice.class);
    
    Files upload public
    static void upload (file file, netcallback<object> callback) {
        Requestbody BODY = requestbody . Create (Mediatype.parse ("Multipart/form-data"), file);
        Multipartbody.part part = MultipartBody.Part.createFormData ("File", File.getname (), body);
        Call call = Service.upload (part);
        Call.enqueue (callback);
        Netmanager.addrequest (call);
    }


Test Call:

public class Test {public
    static void Main (string[] args) {
        String FilePath = "e://forgotten time. Ape";
        File File = new file (FilePath);
        Netcallback<object> callback = new netcallback<object> () {
            @Override
            protected void OnComplete ( Netresponse<object> netresponse) {
            }
        };
        Testapi.upload (file, callback);
    }

Test successfully uploaded ...

Third, HTML5 page single file upload and multiple file upload

<! DOCTYPE html>

Test Success!!!!!!!!!!!!!!!!!!!!!!!



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.