1.表单上传;
先获取到part对象,然后在通过part对象读取输入流(inputStream),最后把文件写到特定的目录上即可;
表单上传的前端代码:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
【图片|图片 上传 java_java web原始的图片上传示例】resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter()
.append("")
.append("
") .append("")
.append("
") .append("
") .append("文件上传示例")
.append("")
.append("
" + "
") .append("
.append("
.append("
") .append("")
.append("");
}
表单上传的后台处理代码:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json");
resp.setCharacterEncoding("utf-8");
Part part = req.getPart("file");
String file = "{";
file += "\"name\":\"" + part.getName()+"\",\n";
file += "\"contentType\":\"" + part.getContentType()+"\",\n";
file += "\"size\":\""+part.getSize()+"\",\n";
file += "\"url\":\"/upload/"+part.getSubmittedFileName()+"\",\n";
file += "\"submitFileName\":\""+part.getSubmittedFileName()+"\"}";
BufferedInputStream bufferedInputStream = new BufferedInputStream(part.getInputStream());
FileOutputStream outputStream = new FileOutputStream("d:/tmp/"+part.getSubmittedFileName());
int read;
while ((read = bufferedInputStream.read()) != -1){
outputStream.write(read);
}
outputStream.close();
bufferedInputStream.close();
resp.getWriter()
.append(file);
}
2.js上传;
可以把图片通过FileReader对象读取转换成base64的文字,然后通过ajax上传到服务器,这个稍微简单很多.
服务器获取到上传的文本,通过分割及解密的方式,输出到存储目录中即可.
下面是base64处理的方法:
public void uploadBase64(String fieldName){
String savePath = "d:/tmp/";
String base64Data = https://www.it610.com/article/this.request.getParameter(fieldName);
this.fileName = "test.jpg";
this.url = savePath + this.fileName;
BASE64Decoder decoder = new BASE64Decoder();
try {
File outFile = new File(this.getPhysicalPath(this.url));
OutputStream ro = new FileOutputStream(outFile);
byte[] b = decoder.decodeBuffer(base64Data);
for (int i = 0;
i < b.length;
++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
ro.write(b);
ro.flush();
ro.close();
this.state=this.errorInfo.get("SUCCESS");
} catch (Exception e) {
this.state = this.errorInfo.get("IO");
}
}
推荐阅读
- java|java web 上传文件到数据_JAVA WEB文件上传步骤
- 文件上传|文件上传 java web_JavaWeb:实现文件上传
- Java/C|C语言指针初阶
- mall学习教程|再见 Xshell ,这款开源的终端工具逼格更高~
- math.h|手撕前端面试代码题大全
- Java入门:初学者怎样学习JAVA?值得收藏!
- 字符串|Babel是如何读懂JS代码的
- xml 中 sql 模糊查询like
- 程序员成长之路|项目实战(P 14)(Day 42)