web端 上传图片 到服务器保存【不同方式 :javaweb、nodejs、django】
实例
- 方式一:Nodejs
- 方式二:Javaweb
- 方式三:Javaweb
- 四、Django
方式一:Nodejs
前端代码:
<input type="file" name="" id="file"><button onclick="doUpload()">上传文件</button><img src="" alt="" id="img"><script> function doUpload(){ let file = $("#file").get(0).files[0]; // 获取上传文件的数据 // 将图片转换为 formData对象 let formdata = new FormData() formdata.append("upload_name",file) console.log("开始上传~") $.ajax({ url: "http://localhost:3000/upload", type: "POST", cache: false, // 不必须 data:formdata, processData: false, // 必须 contentType: false,// 必须 success: function(data){ console.log(data); if(data.err==0){ $("#img").attr("src",data.imgUrl); }else{ alert("上传失败!") } } }) }</script>
服务器代码:
const express = require("express");const request = require('request');const path = require('path');const multer = require("multer");const app = express();// 配置 multer:缓存var storage = multer.diskStorage({ // 1. 设置上传后文件的路径,uploads文件夹会自动创建(最好手动建好) destination:function (req,file,cb) { cb(null,"./uploads") }, // 2. 给上传的文件重命名,获取添加后缀名 filename:function (req,file,cb) { // 前端上传的文件名 let filename = req.body.filename; var fileFormat = (file.originalname).split("."); // 给图片加上时间戳,可防止文件名字重复; fileFormat[fileFormat.length - 1]这里-1是取最后的后缀,因为'.'的个数多个 cb(null,file.fieldname '-' Date.now() '.' fileFormat[fileFormat.length - 1]) }});var upload = multer({ storage:storage});// 接口:上传图片必须使用post方法// uploads.single("name") 里面是上传图片的key值,这个必须和前端统一,不然上次不成功app.post("/upload",upload.single("upload_name"),(req,res)=>{ console.log(req.file); // 前端上传的文件名 let filename = req.body.filename; let {size,mimetype,path} = req.file; let types = ['jpg','jpeg','png','gif']; // 允许上传的文件类型 let tmpType = mimetype.split("/")[1]; if(size>500000){ return res.send({err:-1,msg:"文件太大"}); }else if(types.indexOf(tmpType)==-1){ return res.send({err:-2,msg:"媒体类型错误"}); }else{ let url = `/upload/${req.file.filename}` res.send({err:0,imgUrl:url}); }});// 开启服务器app.listen(3000,function (request,response) { console.log("服务器启动~~~");});// 开放静态目录(上传图片保存的位置,可以url访问)let upload_path = path.join(__dirname,"./uploads"); // 实现路径拼接app.use("/upload",express.static(upload_path));
方式二:Javaweb
前端代码:
<script>var reader = new FileReader();reader.readAsDataURL(document.getElementById("product-img-input").files.item(0));reader.onload = function () { var productImgBase64 = this.result; $.ajax({ url: "/ProductAdd", type: "POST", dataType: 'json', data: {"productImg": productImgBase64}, success: function (response) { console.log("上传成功"); }, });};</script>
服务器接收:
import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import java.io.*;public class Base64Utils { // 函数1:将数据data转成png存到src/image下命名位id.png public static void saveBase64DataToPng(String data, int id) { try { BASE64Decoder decoder = new BASE64Decoder(); String path = Base64Utils.class.getResource("").getPath().split("out/")[0] "src/images/" id ".png"; FileOutputStream write = new FileOutputStream(new File(path)); byte[] decoderBytes = decoder.decodeBuffer(data.split(",")[1]); write.write(decoderBytes); write.close(); } catch (Exception e) { e.printStackTrace(); } } // 函数2:根据id找到id.png的图片转成base64返回 public static String PngToBase64(int id) { InputStream in = null; byte[] data = null; String path = Base64Utils.class.getResource("").getPath().split("out/")[0] "src/images/" id ".png"; try { in = new FileInputStream(path); data = new byte[in.available()]; in.read(data); in.close(); } catch (Exception e) { e.printStackTrace(); } BASE64Encoder encoder = new BASE64Encoder(); return "data:image/png;base64," encoder.encode(data).replace("\r\n",""); }}
方式三:Javaweb
package util;import com.alibaba.fastjson.JSON;import model.Result;import model.Upload_Result;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.util.*;@WebServlet(name = "uploadPicture", urlPatterns = "/uploadPicture")public class uploadPicture extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { System.out.println("接收图片----"); if(!ServletFileUpload.isMultipartContent(request)){ throw new RuntimeException("当前文件不支持文件上产"); } System.out.println("接收图片完成----"); String path = request.getSession().getServletContext().getRealPath("/upload"); System.out.println(path); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(path)); factory.setSizeThreshold(1024 * 1024); ServletFileUpload upload = new ServletFileUpload(factory); System.out.println(upload); List<FileItem> items=null; try { System.out.println("000000000000----"); items = upload.parseRequest(request); System.out.println("大小:" items.size()); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); String picPath = ""; while (iter.hasNext()) { System.out.println("111111111111111111111"); FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { // 根据时间戳创建头像文件 String filename = System.currentTimeMillis() ".jpg"; System.out.println(request.getContextPath()); //项目下创建文件夹 File f = new File(getServletContext().getRealPath("upload")); // D盘的存放文件夹// File f = new File("D://javaWebUploadFile"); if (!f.exists()) { f.mkdir(); } String imgsrc = f "/" filename; System.out.println(imgsrc); // /reports/1551435783395.jpg picPath = "/upload/" filename; // 复制文件 InputStream is = item.getInputStream(); FileOutputStream fos = new FileOutputStream(imgsrc); byte b[] = new byte[1024 * 1024]; int length = 0; while (-1 != (length = is.read(b))) { fos.write(b, 0, length); } fos.flush(); fos.close(); } else { System.out.println(item.getFieldName()); String value = item.getString(); value = new String(value.getBytes("ISO-8859-1"), "UTF-8"); System.out.println(value); } } ArrayList<Object> lst=new ArrayList<>(); Upload_Result result_data=new Upload_Result(); result_data.setFile(picPath); lst.add(result_data); Result result=new Result(); result.setCode(0); result.setMsg("请求成功"); result.setCount(10); result.setData(lst); String content= JSON.toJSONString(result); // 3.发送数据 response.setCharacterEncoding("UTF-8"); //通知浏览器使用utf-8解码 response.setHeader("Content-type", "text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.write(content); }}
四、Django
网页表单端加上enctype=“multipart/form-data”
注意:setting.py配置
STATIC_URL = '/static/'MEDIA_URL = '/media/'STATICFILES_DIRS=( os.path.join(BASE_DIR, 'media'), os.path.join(BASE_DIR,"static"),)
前端:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>上传图片</title></head><body><form action="/upload/" method="POST" enctype="multipart/form-data"> <input type="file" name="imgFile"><br/><br/> <input type="submit" value="上传"></form></body></html>
后端:
from django.urls import pathfrom django.shortcuts import render,redirect,HttpResponsefrom uploadImg import settingsdef get_uploadHtml(request): if request.method=="GET": print("获取上传界面~") return render(request,"upload.html")def upload_imgFile(request): if request.method=="POST": print("前端上传图片") # 1. 接收图片 imageFile = request.FILES["imgFile"] print(imageFile) # 2. 验证图片 contentTypes = ['image/jpeg', 'image/png', 'image/gif','image/bmp'] if imageFile.content_type not in contentTypes: return HttpResponse('图书格式错误', '请上传图片格式') # 3. 保存图片 # save_path = '%s%s%s' % (settings.BASE_DIR,settings.MEDIA_URL, imageFile.name) # 绝对路径保存 save_path = 'static/' imageFile.name # 相对路径保存 print("save_path:",save_path) with open(save_path, 'wb ') as f: f.write(imageFile.read()) return HttpResponse("上传成功,可访问:" "http://127.0.0.1:8000/" save_path)urlpatterns = [ path('gethtml/', get_uploadHtml), path('upload/', upload_imgFile),]
访问静态目录:
注意:setting.py配置
下面配置是添加了两个文件夹作为静态目录,但是访问时,都是http://localhost:8000/static/***
,都是static开始噢 !!!然后才是文件名。
STATIC_URL = '/static/'STATICFILES_DIRS=( os.path.join(BASE_DIR, 'media'), os.path.join(BASE_DIR,"static"),)
来源:https://www.icode9.com/content-1-868601.html
赞 (0)