您好,登錄后才能下訂單哦!
先附上圖片上傳的代碼
jsp代碼如下:
<form action="${path}/upload/uploadPic.do" method="post" enctype="multipart/form-data"> <div> ![](${path}/mall/image/load_image.png) <input type="file" id="input-image" name="input-image"> <input id="input-relative-path" name="imgs" type="hidden" > <input id="input-last-path" type="hidden"> <input type="submit" value="上傳圖片"> </div> </form>
controller代碼:通過spring的方式實現
@Controller @RequestMapping("/upload") public class UploadController extends BaseController { @RequestMapping(value = "/uploadPic", method = RequestMethod.POST) @LoginCheck public void uploadPic(HttpServletRequest request, PrintWriter out, String lastRealPath) throws IOException { // 將當前上下文初始化給CommonsMultipartResolver CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext()); // 檢查form中是否有enctype="multipart/form-data" if (resolver.isMultipart(request)) { // 強制轉化request MultipartHttpServletRequest req = (MultipartHttpServletRequest) request; // 從表單獲取input名稱 Iterator<String> iterable = req.getFileNames(); // 存在文件 if (iterable.hasNext()) { String inputName = iterable.next(); // 獲得文件 MultipartFile mf = req.getFile(inputName); byte[] mfs = mf.getBytes(); // 定義文件名 String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); Random random = new Random(); for (int i = 0; i < 3; i++) { fileName = fileName + random.nextInt(10); } // 獲得后綴名 String oriFileName = mf.getOriginalFilename(); String suffix = oriFileName.substring(oriFileName.lastIndexOf(".")); // 上傳圖片到本地 String localPath = "/Users/ZR/Desktop/webPro/console/src/main/webapp/image/" + fileName + suffix; mf.transferTo(new File(localPath)); // 獲取圖片的寬高 BufferedImage bufferedImage = ImageIO.read(new FileInputStream(new File(localPath))); int width = bufferedImage.getWidth(); int height = bufferedImage.getHeight(); // 獲取文件大小 long size = mf.getSize(); } } } }
spring-mvc.xml代碼:
<!-- 文件上傳的視圖解析器,id值是固定的 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="1024000"/> <!-- 其他屬性 --> </bean>
功能的實現其實很簡單,但是對于初學者還是需要注意如下幾個點
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。