Java method for uploading file images to server
- 2020-12-18 01:50:39
- OfStack
Here I record a relatively simple and convenient JAVA to upload files and pictures to the server and save them, the specific content is as follows
First is the page html of me which is to submit 1 file and type
<div style="border: 1px solid red;">
I am adding 1 It's a temporary picture that gets WeChat media_id Save database !
<form action="xxxxxxxxm"
enctype="multipart/form-data" method="post">
<div style="display: none;">
<input type="text" value="IMAGE" name="type"/>
</div>
To upload pictures :<input type="file" name="file"
onchange="previewImage(this, 'prvid')" multiple="multiple"><br />
<input type="submit" value=" submit " />
</form>
<div id="prvid"> Preview the container </div>
</div>
Preview image js
function previewImage(file, prvid) {
/* file : file controls
* prvid: Picture preview container
*/
var tip = "Expect jpg or png or gif!"; // Setting prompt message
var filters = {
"jpeg" : "/9j/4",
"gif" : "R0lGOD",
"png" : "iVBORw"
}
var prvbox = document.getElementById(prvid);
prvbox.innerHTML = "";
if (window.FileReader) { // html5 plan
for (var i = 0, f; f = file.files[i]; i++) {
var fr = new FileReader();
fr.onload = function(e) {
var src = e.target.result;
if (!validateImg(src)) {
alert(tip)
} else {
showPrvImg(src);
}
}
fr.readAsDataURL(f);
}
} else { // down-cycled
if (!/\.jpg$|\.png$|\.gif$/i.test(file.value)) {
alert(tip);
} else {
showPrvImg(file.value);
}
}
function validateImg(data) {
var pos = data.indexOf(",") + 1;
for ( var e in filters) {
if (data.indexOf(filters[e]) === pos) {
return e;
}
}
return null;
}
function showPrvImg(src) {
var img = document.createElement("img");
img.src = src;
prvbox.appendChild(img);
}
}
And then you get the background
@RequestMapping(params = "method=addCircle")
public String addCircle(HttpServletResponse response,HttpServletRequest request) throws IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String path = request.getSession().getServletContext().getRealPath(
"/BackstageShoppingWebsite/images/addCircleimage");// Saved server address
Map<String, String> map = Upload
.upload(request, 1024 * 1024 * 10, path);
String file= map.get("file"); // The name of the
String image = map.get("type"); // image
String newFile = map.get("newFile");// address
return null;
}
Ok, now the point is to look at the Upload class which is basically encapsulated, you can take whatever you need to add and modify it, and then this class uses the cos.jar package
package com.web.weixin.bean;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.oreilly.servlet.multipart.FilePart;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.ParamPart;
import com.oreilly.servlet.multipart.Part;
public class Upload {
public static Map<String, String> upload(HttpServletRequest request,
int maxSize, String path) {
// In order to map Form saving data key The corresponding save is on the get interface name The name of the value Save is on the get screen name The value of the corresponding
Map<String, String> map = new HashMap<String, String>();
Part part = null;
try {
MultipartParser mrequest = new MultipartParser(request, maxSize);
mrequest.setEncoding("utf-8");
// I'm going through all of them part group
while ((part = mrequest.readNextPart()) != null) {
if (part.isFile()) { // Determine if it's a file
FilePart filepart = (FilePart) part;// Convert to file group
String fileName = filepart.getFileName();// Get the file name
if (fileName != null && fileName.length() > 0) {
// Get the extension
String fileExtName = fileName.substring(
fileName.lastIndexOf(".") + 1).toLowerCase();
// Upload pictures only // Determine if the image is uploaded in the right format Whether the suffix name is valid
if (fileExtName.equalsIgnoreCase("jpeg")
|| fileExtName.equalsIgnoreCase("png")||
fileExtName.equalsIgnoreCase("jpg")
|| fileExtName.equalsIgnoreCase("gif")
|| fileExtName.equalsIgnoreCase("ico")
|| fileExtName.equalsIgnoreCase("bmp")
|| fileExtName.equalsIgnoreCase("flv")
|| fileExtName.equalsIgnoreCase("mp4")
|| fileExtName.equalsIgnoreCase("mp3")) {
/*String newFileName = new Date().getTime() + "."+ fileExtName;
// Rename file The file name + extension */
String newFileName =new Date().getTime() +fileName;// Do not change the name of the picture
String newPath = path + "/" + newFileName; // File handles the path to file uploads
File newFile = new File(newPath);
filepart.writeTo(newFile); // Actually write the file to the corresponding folder
//filepart.getName() get request The name of the parameter to receive
map.put(filepart.getName(), newFileName);// Save the file information to map In the
map.put("newFile", newFile.toString());
} else {
map.put("geshi", "geshi");
continue;
}// This is not a picture
} else {
map.put("yes","yes");
continue; // Note that you did not choose to upload the image
}
} else if (part.isParam()) { // Determine if it is a parameter
ParamPart paramPart = (ParamPart) part;
map.put(paramPart.getName(), paramPart.getStringValue());
}
}
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
To download the cos.jar package, click the open link
This article has been compiled in Java Upload operation Skills Summary, welcome to learn to read.