I have always uploaded files using form forms to upload files. I have also seen people upload files using js, but it seems quite simple, so I didn't pay much attention to it. Today I suddenly wanted to use this method to upload files, and I encountered some problems during this period. Therefore, it is recorded so that you can check it if you encounter such problems in the future.
The first thing is to introduce js and ajaxfileupload files, which need not be said much.
Then there is ajax requesting the background address. The code is as follows:
<div> <input type="file" id="upload" name="upload" style="font-size: 0;opacity: 0;width: 100%;height: 100%;position: absolute;left: 0;top: 0;"/> <span>Select file</span> </div> $("#upload").on("change",function(){ $.ajaxFileUpload({ url : '/test/user/imgUpload',//Backend request address type: 'post',//Request method When you want to submit a custom parameter, this parameter must be set to post secureuri : false,//Whether to enable secureuri, the default is false. fileElementId : 'upload',// The ID of the file domain that needs to be uploaded, that is, the ID of <input type="file">. dataType : 'json',//The data type returned by the server can be xml, script, json, html. If not filled in, jQuery will automatically judge. If the json returns with pre, it can be modified to json to solve it. success : function (json, status) {//The processing function automatically executed after the submission is successful, and the parameter data is the data returned by the server. alert(json.retMsg); }, error : function (json, status, e) {//The processing function automatically executed after the submission is failed. } }); });When the front-end code is completed, the background code will be developed.
package com.roc.test;import java.io.File;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.ws.rs.Consumes;import javax.ws.rs.POST;import javax.ws.rs.Path;import javax.ws.rs.Produces;import javax.ws.rs.QueryParam;import javax.ws.rs.core.Context;import javax.ws.rs.core.MediaType;import net.sf.json.JSONObject;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.jboss.resteasy.annotations.providers.jaxb.json.BadgerFish;import org.springframework.stereotype.Controller;import net.sf.json.JSONObject;/** * Upload file* @author liaowp * */@Controller@Path("/user")public class UploadImg { @Path("/imgUpload") @POST @Produces("application/json; charset=utf-8") @Consumes(MediaType.MULTIPART_FORM_DATA ) @BadgerFish public JSONObject upload(@QueryParam("orderId") String orderId,@Context HttpServletRequest request,@Context HttpServletResponse response) { JSONObject jsonobj = new JSONObject(); String file_path=request.getSession().getServletContext().getRealPath("/")+File.separator+"corpfile"+File.separator;//File storage path String upload_file_path=""; File file =new File(file_path); if(!file.exists() && !file.isDirectory()){ //If the folder does not exist, create file.mkdir(); upload_file_path=file_path; }else{ upload_file_path=file_path; } DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory factory.setRepository(new File(file_path));// Set file storage location factory.setSizeThreshold(2048 * 1024);// Set size, if the file is smaller than the set size, put it in memory, if it is larger than it is placed in disk ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8");// This is the code for processing Chinese filenames. In fact, there is only one line String fileName = ""; List<FileItem> list; JSONObject jsonobj = new JSONObject(); try { list = upload.parseRequest(request); for (FileItem item : list) { if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString("utf-8"); } else { String name = item.getFieldName(); String value = item.getName(); fileName =name + ".jpg"; if (item.getSize() > 10485760) {//Hello, the upload file must be less than 10M! jsonobj.put("retCode","100"); jsonobj.put("retMsg","Hello, uploading the file should be less than 10M!"): } else {//Upload successfully item.write(new File(upload_file_path, fileName)); System.out.println(File.separator + "corpfile" + File.separator + fileName); jsonobj.put("retCode","0"); jsonobj.put("retMsg","Hello, upload successfully!"); } } } } } catch (Exception e) {//Upload failed e.printStackTrace(); jsonobj.put("retCode","9999"); jsonobj.put("retMsg","Hello, file upload failed,"); } return jsonobj; }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.