Almost every program needs images. In the applet we can display the image through the image component.
Of course, small programs can also upload pictures, micro channel small program documentation is also written very clearly.
## Upload pictures
I’m gonna go ahead and select the image
Wx.chooseimage (OBJECT)
Official sample code
Wx. chooseImage({count: 1, // default 9 sizeType: ['original'.'compressed'], // You can specify whether the image is original or compressed. By default, both are availablesourceType: ['album'.'camera'], // You can specify whether the source is photo album or camera, and default to both success:function(res) {// Returns a list of local file paths for the selected photos. TempFilePath can be used as a SRC property to display images var tempFilePaths = res.tempfilepaths}})Copy the code
You can select a maximum of nine images or take photos. After you select an image, you can obtain the image path, which is valid during this startup. Wx.savefile (OBJECT) if you want to save it
To upload pictures
Wx. uploadFile(OBJECT) allows you to upload local resource files to the server.
The principle is that the client initiates an HTTPS POST request, where the content-type is multipart/form-data.
Official sample code
wx.chooseImage({
success: function(res) {
var tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'http://example.weixin.qq.com/upload'FilePath: tempFilePaths[0], name:'file',
formData:{
'user': 'test'
},
success: function(res){
var data = res.data
//do something
}
})
}
})
Copy the code
After reading the documentation, it is not so troublesome to write an upload image. Here is the code for the real scene
import constant from '.. /.. /common/constant';
Page({
data: {
src: ".. /.. /image/photo.png"// bind image component SRC // }, onLoad:function(options) {//... },uploadPhoto() { var that = this; Wx. chooseImage({count: 1, // default 9 sizeType: ['compressed'], // You can specify whether the image is original or compressed. By default, both are availablesourceType: ['album'.'camera'], // You can specify whether the source is photo album or camera, and default to both success:functionVar tempFilePaths = res.tempfilepaths; (res) {// Returns the list of local file paths for the selected photos. upload(that, tempFilePaths); }})}})function upload(page, path) {
wx.showToast({
icon: "loading",
title: "Uploading"
}),
wx.uploadFile({
url: constant.SERVER_URL + "/FileUploadServlet",
filePath: path[0],
name: 'file',
header: { "Content-Type": "multipart/form-data"}, formData: {// The token specified by the server can also be placed in the header'session_token': wx.getStorageSync('session_token')
},
success: function (res) {
console.log(res);
if(res.statusCode ! = 200) { wx.showModal({ title:'tip',
content: 'Upload failed',
showCancel: false
})
return; } var data = res.data page.setdata ({// upload successfully modify display profile picture SRC: path[0]})}, fail:function (e) {
console.log(e);
wx.showModal({
title: 'tip',
content: 'Upload failed',
showCancel: false
})
},
complete: function() { wx.hideToast(); // Hide Toast}})}Copy the code
The back-end code
The back end is written in Java, at the beginning, the back end started to use some framework to receive uploaded images, there were various problems, later using pure Servlet no problem, the code posted to save the trouble in the future. Note: the code uses the company’s internal framework, it is recommended to modify before use
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(FileUploadServlet.class);
public FileUploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JsonMessage<Object> message = new JsonMessage<Object>();
EOSResponse eosResponse = null;
String sessionToken = null;
FileItem file = null;
InputStream in = null;
ByteArrayOutputStream swapStream1 = null;
try {
request.setCharacterEncoding("UTF-8"); DiskFileItemFactory factory = new DiskFileItemFactory(); // create a file upload resolver ServletFileUpload upload = new ServletFileUpload(factory); Upload. SetHeaderEncoding ("UTF-8"); Items List<FileItem> items = upload.parseRequest(request); logger.info("items:{}", items.size()); // 2. Iterate through items:for (FileItem item : items) {
String name = item.getFieldName();
logger.info("fieldName:{}", name); // If it is a normal form field, print the informationif (item.isFormField()) {
String value = item.getString("utf-8");
if("session_token".equals(name)){ sessionToken = value; }}else {
if("file".equals(name)){ file = item; }}} // Session verificationif(StringUtils.isEmpty(sessionToken)){
message.setStatus(StatusCodeConstant.SESSION_TOKEN_TIME_OUT);
message.setErrorMsg(StatusCodeConstant.SESSION_TOKEN_TIME_OUT_MSG);
}
String userId = RedisUtils.hget(sessionToken,"userId");
logger.info("userId:{}", userId);
if(StringUtils.isEmpty(userId)){ message.setStatus(StatusCodeConstant.SESSION_TOKEN_TIME_OUT); message.setErrorMsg(StatusCodeConstant.SESSION_TOKEN_TIME_OUT_MSG); } // Upload the fileif(file == null){
}else{
swapStream1 = new ByteArrayOutputStream();
in = file.getInputStream();
byte[] buff = new byte[1024];
int rc = 0;
while ((rc = in.read(buff)) > 0) {
swapStream1.write(buff, 0, rc);
}
Usr usr = new Usr();
usr.setObjectId(Integer.parseInt(userId));
final byte[] bytes = swapStream1.toByteArray();
eosResponse= ServerProxy.getSharedInstance().saveHeadPortrait(usr, new RequestOperation() {
@Override
public void addValueToRequest(EOSRequest request) {
request.addMedia("head_icon_media", new EOSMediaData(EOSMediaData.MEDIA_TYPE_IMAGE_JPEG, bytes)); }}); // Request successif (eosResponse.getCode() == 0) {
message.setStatus(ConstantUnit.SUCCESS);
} else {
message.setStatus(String.valueOf(eosResponse.getCode()));
}
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(swapStream1 ! = null){ swapStream1.close(); } } catch (IOException e) { e.printStackTrace(); } try {if(in! = null){ in.close(); } } catch (IOException e) { e.printStackTrace(); } } PrintWriter out = response.getWriter(); out.write(JSONObject.toJSONString(message)); } protected voiddoPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response); }} ` ` `Copy the code