圖片上傳前端的幾種方法
阿新 • • 發佈:2018-11-26
1.路徑
<img src="balabala/123.jpg">
2.img標籤指向servlet方法
<img src="/ImgServlet?imgId=00001" alt="picture">
主要流程為:獲取id—>查詢資料庫得到圖片路徑—>重置response—>得到輸出流—>設定contenttype—>讀取檔案流—>輸入快取區—>輸出快取區—>緩衝位元組數
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String imgId = request.getParameter("imgId"); String imagePath = getImagePathFromDB(imgId); response.reset(); OutputStream output = response.getOutputStream(); response.setContentType(GIF); ServletContext context = getServletContext(); InputStream imageIn = context.getResourceAsStream(imagePath); BufferedInputStream bis = new BufferedInputStream(imageIn); BufferedOutputStream bos = new BufferedOutputStream(output); byte data[] = new byte[4096]; int size = 0; size = bis.read(data); while (size != -1) { bos.write(data, 0, size); size = bis.read(data); } bis.close(); bos.flush(); bos.close(); output.close(); }
3.二進位制流顯示圖片(不存到本地)
將圖片轉換成資料流,然後將資料流一對一將傳進轉化為陣列的MemoryStream中,通過image控制元件顯示圖片
string path = "https://img3.doubanio.com/mpic/s8896281.jpg"; Uri url = new Uri(path); WebRequest webRequest = WebRequest.Create(url); WebResponse webResponse = webRequest.GetResponse(); Bitmap myImage = new Bitmap(webResponse.GetResponseStream()); MemoryStream ms = new MemoryStream(); myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); var p = new pictureUrl { pictureUrl1 = ms.ToArray() }; db.pictureUrl.InsertOnSubmit(p); db.SubmitChanges();
var pictures = from picture in db.pictureUrl select picture;
pictureUrl myPicture = pictures.First();
MemoryStream mymemorystream = new MemoryStream(myPicture.pictureUrl1.ToArray());
pictureBox1.Image = Image.FromStream(mymemorystream);
4.圖片轉化為base64字串
將圖片轉化為位元組字串陣列,並對其進行編碼處理,再解碼生成圖片
http://blog.sina.com.cn/s/blog_6400e5c50101qtr3.html
https://blog.csdn.net/hanchao5272/article/details/79261312
http://www.cnblogs.com/JsonZhangAA/p/5568575.html
http://www.cnblogs.com/JsonZhangAA/p/5574685.html