background
Uploading files by WeChat applet is one of the APIs provided by WeChat applet. If you use JAVA backend, how to process uploaded files?
Official document
UploadTask wx.uploadFile(Object object)
Upload local resources to the server. The client initiates an HTTPS POST request, which
content-type
ismultipart/form-data
.parameter
Object object
Attributes Types of Defaults Required Description Minimum version url string Yes Developer server address filePath string Yes Path to upload file resource (local path) name string Yes The key corresponding to the file, the developer can get the binary content of the file through this key on the server header Object no HTTP request Header, Referer cannot be set in Header formData Object no Other additional form data in the HTTP request timeout number no Timeout period, in milliseconds 2.10.0 success function no Callback function for successful interface call fail function no Callback function for interface call failure complete function no The callback function for the end of the interface call (the call will be executed if it succeeds or fails) object.success callback function
parameter
Object res
Attributes Types of Description data string Data returned by the developer server statusCode number HTTP status code returned by the developer server
Create small programs and write code
Let’s not talk about creating a small program. If you are not developing a small program, you will not be involved in uploading files. The key code uploaded is as follows
wx.uploadFile({
url: getApp().globalData.host + '/uploadImage',
filePath: "/images/full_cart.png",
name: 'img',
success: (res) => {
console.log("upload succeed")
var data = res.data;
console.log(data);
}, fail: () => {
console.log("upload failed")
}
})
There are three key parameters for the above code upload file.
The first parameter: url. This parameter is the address of the server. In this article, our server is the local Tomcat, so naturally it is localhost:8080, or it can be written directly as url:'http://localhost:8080/uploadImage' . uploadImage represents the address of the Controller, which will be discussed below.
According to the above writing method, because I made a global configuration in App.js,
globalData: {
host: 'http://localhost:8080',
}
The second parameter: filePath. This parameter is the file I want to upload
The third parameter name is the key set for this image object. Used in Controller.
JAVA background project creation and coding
JAVA backend is also called JAVA backend, in short it means server.
The choice here is the Maven project created by Spring Boot, a Controller is created in the project ratio, and coded. code show as below.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* @author kangyucheng
*/
@Controller
public class UploadController {
private final static Logger logger = LoggerFactory.getLogger(UploadController.class);
@PostMapping("/uploadImage")
@ResponseBody
public String uploadImageFile(@RequestParam("img") MultipartFile uploadImage) throws IOException {
String fileName = uploadImage.getOriginalFilename();
String imgFilePath = "/Users/yuchk/Desktop/";
File targetFile = new File(imgFilePath, fileName);
//保存
uploadImage.transferTo(targetFile);
logger.info("图片存储成功");
return "success";
}
}
have to be aware of is
@PostMapping("/uploadImage") should be consistent with the address in the url parameter in the WeChat applet, and
@RequestParam("img") should be the same as the name in the WeChat applet.
Local debugging
In the process of local debugging, the Spring boot project must first be started.
Then compile the applet to trigger the upload event.
Remember to enable non-verification of legal domain names.
Local debugging results
Real machine debugging
Since the server is started locally, it will inevitably fail if the real machine cannot access the local server.
Backstage error trap
Assuming that there is an abnormality in our background, the WeChat applet cannot handle it. It will still be treated as a successful upload.
Modify code
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* @author kangyucheng
*/
@Controller
public class UploadController {
private final static Logger logger = LoggerFactory.getLogger(UploadController.class);
@PostMapping("/uploadImage")
@ResponseBody
public String uploadImageFile(@RequestParam("img") MultipartFile uploadImage) throws Exception {
String fileName = uploadImage.getOriginalFilename();
String imgFilePath = "/Users/yuchk/Desktop/";
File targetFile = new File(imgFilePath, fileName);
//保存
uploadImage.transferTo(targetFile);
logger.info("图片存储成功");
throw new Exception("故意的,哈哈");
}
}
The file upload event is triggered locally again.
Conclusion: It is necessary to determine whether the file is uploaded successfully according to different returned results.
Other things to note
If you forget to write the @ResponseBody annotation, this may be the case. Although the image is uploaded successfully, the content returned to the WeChat applet is not our preset content.
If the return is a custom class, then an error will also occur.
/**
* @author kangyucheng
*/
@Controller
public class UploadController {
private final static Logger logger = LoggerFactory.getLogger(UploadController.class);
@PostMapping("/uploadImage")
@ResponseBody
public M uploadImageFile(@RequestParam("img") MultipartFile uploadImage) throws Exception {
String fileName = uploadImage.getOriginalFilename();
String imgFilePath = "/Users/yuchk/Desktop/";
File targetFile = new File(imgFilePath, fileName);
//保存
uploadImage.transferTo(targetFile);
logger.info("图片存储成功");
return new M("a","b");
}
}
class M{
String a;
String b;
public M(String a,String b){
this.a = a;
this.b = b;
}
}