JavaWeb uploaded images in several ways

I. Introduction upload pictures

JavaWeb direction of the programming process, to achieve upload pictures in three ways:

1, based on the traditional springMVC of MultipartFile class implements image upload.

2, Ajax-based image upload.

3, Base64 compressed images based uploading.

Two, springMVC upload pictures (springboot Universal)

The advantage of this method is to be submitted to the server along with photographs and other form elements, server receives the picture is already stored in a temporary file container, copy work files is relatively simple.

The disadvantage is that not in time to see an image preview upload pictures once the wrong choice can only be re-submitted.

Note: Code Red is the key to the code.

1, page code

<form action="/upload" method="post" enctype="multipart/form-data">
    选择头像:<input type="file" name="file" accept="image/*" /> <br>
    用户名字:<input type="text" name="userName"/> <br>
    <input type="submit" value="提交">
</form>

2, config.properties profile

** This configuration file contents can be written in springboot application.properties file **

file.location.path=d:/upload

 

3, spring-servlet.xml profile 

** This profile does not require configuration in springboot - the "habit higher than the configured" **

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsddefault 
    <-! parsing path turning pages. prefix: prefix, suffix: suffix -> 
    <the bean
    -servlet-handler/>class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            p:prefix="/" p:suffix=".jsp"/>
    <!--文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600"/>
        <property name="maxInMemorySize" value="4096"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
</beans>

 

4, controller codes

@Controller
public class UserController {
    @Autowired
    UserService userService;
    @Value("${file.location.path}")
    private String fileLocation;
    @RequestMapping("/insert")
    public String insert(User user, MultipartFile file){
        String uri = FileUpload.upload(file,"/upload",fileLocation);
        user.setFacePic(uri);
        int ret = userService.insertUser(user);
        if(ret > 0 ){
            return "redirect:/get";
        }else{
            return "register";
        }
    }
}

 

5, upload tool class code

public  class the FileUpload {
     / ** 
     * @param File upload files 
     * @param virtual file path to path, e.g. / Upload 
     * @param physical path fileLocation file, for example, D: / Upload 
     * @return virtual file path + file name 
     * 
     * fileName.lastIndexOf ( ".") to acquire the suffix 
     * UUID.randomUUID () to obtain a unique identifier to ensure the uniqueness of the file 
     * / 
    public  static String the Upload (MultipartFile file, String path, String filelocation) { 
        String fileFinishName = null ;
         the try {
             // If the directory does not exist, create
            Uploaddir = File new new File (FileLocation);
             IF (! {UploadDir.exists ()) 
                uploadDir.mkdir (); 
            } 
            // Get the name of the source file 
            String fileName = file.getOriginalFilename (); 
            fileFinishName = UUID.randomUUID () + fileName .substring ( "." fileName.lastIndexOf ( ), FileName.Length ());
             // upload the file to the specified directory 
            file the uploadFile = new new file (uploaddir uploadDir.separator + + fileFinishName); 
            file.transferTo (the uploadFile); 
        } the catch (Exception EX) { 
            ex.printStackTrace ();
        }
        return path + "/" + fileFinishName;
    }
}

 

Second, based on Ajax image upload

This embodiment is the same as the first embodiment using the multipart / form-data upload, the server also uses springMVC (springboot) so inconsistent achieved only page code, other parts (2,3,4,5) supra.

The front-end is the way of jquery.fileupload.js jQuery plug-ins to achieve. Great God see article: https://blog.csdn.net/qq_37936542/article/details/79258158

1, the first page with a jQuery plugin

** ** order can not be wrong

<script src="js/jquery-3.2.1.min.js"></script>
<!-- jquery file upload相关js -->
<script src="js/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script src="js/jquery.fileupload-process.js"></script>
<script src="js/jquery.fileupload-validate.js"></script>

 

2, HTML coding

** ** labels do not need to form

<style>
/* input样式 */
#uploadImg{
display: none;
}
 
/* button样式 */
#chooseFile{
background: #93b6fc;
}
 
#uploadFile,#rechooseFile {
display: none;
background: #93b6fc;
}
 
#image{
  width:200px;
  height:200px;
}
 
/* 进度条样式 */
.bar { 
 background-image: -webkit-linear-gradient(top,#5cb85c 0,#449d44 100%); 
 background-image: -o-linear-gradient(top,#5cb85c 0,#449d44 100%); 
 background-image: -webkit-gradient(linear,left top,left bottom,from(#5cb85c),to(#449d44)); 
 background-image: linear-gradient(to bottom,#5cb85c 0,#449d44 100%); 
 filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0); 
 background-repeat: repeat-x; 
 height: 20px; 
 line-height: 20px; 
 -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15); 
 box-shadow: inset 0 -1px 0 rgba(0,0,0,.15); 
 -webkit-transition: width .6s ease; 
 -o-transition: width .6s ease; 
 transition: width .6s ease; 
}
#progress { 
 filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0); 
 background-repeat: repeat-x; 
 height: 20px; 
 width: 0%; 
 margin-bottom: 20px; 
 overflow: hidden; 
 background-color: #f5f5f5; 
 border-radius: 4px; 
 -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1); 
 box-shadow: inset 0 1px 2px rgba(0,0,0,.1); 
 margin-top: 20px; 
}
</style>
<body>
    <div class="jquery-fileupload">
        <div class="">
            <input id="uploadImg" type="file" name="uploadImg" multiple style="display: none" /> 
                <button id="chooseFile">+选择文件</button> 
                <button id="uploadFile">~开始上传</button>
                <button id="rechooseFile">+重新选择</button>
        </div>
        <div>
            <img id="image" src="">
        </div>
        <div id="progress">
            <div class="bar" style="width: 0%;"></div>
        </div>
    </div>
</body>

 

3, js Code

$ (function () { 
        $ ( "#chooseFile") ON ( "the Click." , function () { 
            $ ( "#uploadImg" ) .click (); 
        }); 
 
        $ ( '#uploadImg' ) .fileupload ({ 
            URL: '/ FileTest / Upload', // target address request sent by 
            the Type: 'the POST', // request mode may be selected POST, PUT or the PATCH, by default the POST
             // dataType: 'JSON', // server returns data type 
            autoUpload: false , 
            acceptFileTypes: / (GIF | JPE G | PNG?) $ / i, // verify that picture format 
            maxNumberOfFiles: 1,// maximum number of files to upload
            the maxFileSize: 1000000, // Maximum file 1MB 
            minFileSize: 100, // File limit 100B 
            messages: { // file error 
                acceptFileTypes: 'does not match the file type' , 
                the maxFileSize: 'file is too large " , 
                minFileSize: ' file is too small ' 
            } 
        }) 
        // event triggered after the addition was complete picture 
        .on ( "fileuploadadd" , function (E, Data) {
             // the validate (data.files [0]) where the file can manually verify the format and size 
            
            // Hide display or page elements 
            $ ( '# .bar Progress' ) .css ( 
                 'width', '0%'
              ); 
            $ ( '#Progress' ) .hide (); 
            $ ( "#chooseFile" ) .hide (); 
            $ ( "#uploadFile" ) the .Show (); 
            $ ( "#rechooseFile" ) the .Show (); 
            
            // get and display the image path 
            var url = getUrl (data.files [0 ]); 
            $ ( "#image") attr ( "src." , url); 
            
            // bind start uploading event 
            $ ( '# uploadFile' ) .click (function () { 
                $ ( "#uploadFile" ) .hide (); 
                jqXHR = data.submit ();
                // unbundling prevent Repeat
                $ ( "# uploadFile") OFF ( "the Click." ); 
            }) 
            
            // bind the click re-election events 
            $ ( "# rechooseFile" ) .click (function () { 
                $ ( "#uploadImg" ) .click () ;
                 // unbundling prevent repeatedly performed 
                $ ( "# rechooseFile") OFF ( "the Click." ); 
            }) 
        }) 
        // when a single file queue process end trigger (verification file format and size) 
        .on ( " fileuploadprocessalways " , function (E, Data) {
             // Get file 
            file data.files = [0 ];
             // get error message 
            IF  (file.error) {
                the console.log (file.error);
                $ ( "#UploadFile" ) .hide (); 
            } 
        }) 
        // show upload progress bar 
        .on ( "fileuploadprogressall" , function (E, Data) { 
            $ ( '#progress' ) the .Show (); 
             var Progress = the parseInt (data.loaded / data.total * 100, 10 ); 
              $ ( '#progress' ) .css ( 
                'width', '15%' 
              ); 
              $ ( '#progress .bar' ) .css ( 
                'width' , Progress + '%' 
              ); 
        }) 
        is triggered when the upload request failed callback function 
        .on("fileuploadfail"//, Function (E, Data) { 
            the console.log (data.errorThrown); 
        }) 
        // upload request triggers the callback success 
        .on ( "fileuploaddone" , function (E, Data) { 
            Alert (data.result); 
            
        }) 
        // after the upload request, regardless of success or abort error will be triggered 
        .on ( "fileuploadalways" , function (E, the Data) { 
 
        }) 
 
        
        // manual verification 
        function the validate (file) {
             // get the file name 
            var = fileName file.name;
             // verify Image format 
            IF (/ (GIF | JPG | jpeg | PNG | GIF | | JPG PNG) $ /!. {.test (fileName)) 
                console.log ("File format is not correct.");
                 Return  to true ; 
            } 
            // verify excell table format 
            / *   IF | $ / the Test (fileName)) {(/ (XLS XLSX!.). 
                 Alert ( "file format is incorrect"); 
                 return to true; 
             } * / 
 
            / / Get file size 
            var = fileSize file.size;
             IF (fileSize> 1024 * 1024 ) { 
                Alert ( "not more than one megabyte file" )
                 return  to true ; 
            } 
            return  to false ; 
        } 
 
        // get image address 
        function getUrl (file) {
            var url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file);
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file);
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file);
            }
            return url;
        }
 
    });

 

Guess you like

Origin www.cnblogs.com/david1216/p/11515246.html