JS 實現上傳照片到伺服器 和 後臺處理處理這個照片
阿新 • • 發佈:2019-02-16
1.js進行圖片預覽 使用input標籤來選擇圖片,使用FileReader讀取圖片並轉成base64編碼,然後傳送給伺服器。
2.伺服器接收資料,然後寫到磁碟<html> <body> <img id="image"src=""/> <br/> <input type="file"onchange="selectImage(this);"/> <br/> <input type="button"onclick="uploadImage();"value="提交"/> <script> var image = ''; function selectImage(file){ if(!file.files || !file.files[0]){ return; } var reader = new FileReader(); reader.onload = function(evt){ document.getElementById('image').src = evt.target.result; image = evt.target.result; } reader.readAsDataURL(file.files[0]); } function uploadImage(){ $.ajax({ type:'POST', url: 'ajax/uploadimage', data: {image: image}, async: false, dataType: 'json', success: function(data){ if(data.success){ alert('上傳成功'); }else{ alert('上傳失敗'); } }, error: function(err){ alert('網路故障'); } }); } </script> <script src="jquery-1.11.1.min.js"></script> </body> </html>
- import java.io.FileOutputStream;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import sun.misc.BASE64Decoder;
-
/**
- * 上傳圖片。
- */
- publicclass UploadImageAjax extends HttpServlet {
- privatestaticfinallong serialVersionUID = 1L;
- @Override
- protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException{
- String image = req.getParameter("image");
- // 只允許jpg
-
String header ="data:image/jpeg;base64,"
- if(image.indexOf(header) != 0){
- resp.getWriter().print(wrapJSON(false));
- return;
- }
- // 去掉頭部
- image = image.substring(header.length());
- // 寫入磁碟
- boolean success = false;
- BASE64Decoder decoder = new BASE64Decoder();
- try{
- byte[] decodedBytes = decoder.decodeBuffer(image);
- String imgFilePath ="D://uploadimage.jpg";
- FileOutputStream out = new FileOutputStream(imgFilePath);
- out.write(decodedBytes);
- out.close();
- success = true;
- }catch(Exception e){
- success = false;
- e.printStackTrace();
- }
- resp.getWriter().print(wrapJSON(success));
- }
- private String wrapJSON(boolean success){
- return"{"success":"+ success +"}";
- }
- }
- <web-app>
- <servlet>
- <servlet-name>UploadImage</servlet-name>
- <servlet-class>UploadImageAjax</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>UploadImage</servlet-name>
- <url-pattern>/ajax/uploadimage</url-pattern>
- </servlet-mapping>
- </web-app>
- 描述: 上傳圖片的project
- 下載次數: 2
http://www.thinksaas.cn/topics/0/348/348211.html